这里介绍两种方式,一种是从服务器下载,一种是从网络上下载
一、从服务器下载
这里path的格式为:D:\testFile\a.jpg,下载后保存在浏览器的下载位置
@RequestMapping("download")
public ResponseEntity<byte[]> download(String path) throws IOException {
// File file=new File(path);
String names[] = path.split("\\.");
String name = DateUtil.getCurrentDate("yyyyMMddHHmmss.") + names[names.length-1];
HttpHeaders headers = new HttpHeaders();
String fileName=new String(name.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
File file = FileUtils.toFile(new URL(path));
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray( file),
headers, HttpStatus.CREATED);
}
这里path的格式为:http://xxx.com/xxx/s_2015072218115087481.jpg
@RequestMapping("download")
public void download(String path,HttpServletResponse response) throws IOException {
byte[] btImg = getImageFromNetByUrl(path);
String fileName = "";
if(null != btImg && btImg.length > 0){
String names[] = path.split("\\.");
fileName = DateUtil.getCurrentDate("yyyyMMddHHmmss.") + names[names.length-1];
writeImageToDisk(btImg, fileName);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + btImg.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(btImg);
outputStream.flush();
outputStream.close();
}
/**
* 根据地址获得数据的字节流
* @param strUrl 网络连接地址
* @return
*/
public static byte[] getImageFromNetByUrl(String strUrl){
<span style="white-space:pre"> </span>try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从输入流中获取数据
* @param inStream 输入流
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
此方法可以下载资源到指定位置
/**
* 将图片写入到磁盘
* @param img 图片数据流
* @param fileName 文件保存时的名称
*/
public static void writeImageToDisk(byte[] img, String fileName){
try {
File file = new File("D:\\" + fileName);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
System.out.println("图片已经写入到C盘");
} catch (Exception e) {
e.printStackTrace();
}
}