String path = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1546100952419&di=4b9466f689800898b761d411c0eed2d2&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F14ce36d3d539b600d3924a1feb50352ac65cb73e.jpg";
try{
URL url = null;
int imageNumber = 0;
try {
url = new URL(path);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
String imageName = "E:/test.jpg";
FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
byte[] context=output.toByteArray();
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
从网络下载图片到本地(尝试成功)
//文件下载相关代码
@GetMapping("/downloadImage")
public String downloadImage( HttpServletResponse response) {
String fileUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1546100952419&di=4b9466f689800898b761d411c0eed2d2&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F14ce36d3d539b600d3924a1feb50352ac65cb73e.jpg";
if (fileUrl != null) {
//下载时文件名称
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/" + 1));
DataInputStream fis = null;
BufferedInputStream bis = null;
try {
URL url = new URL(fileUrl);
fis = new DataInputStream(url.openStream());
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition",
"attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
尝试过已经成功,公司框架是前后端分离的,不明白为啥GetMapping就可以进行下载,但是用PostMapping就不行了,浏览器没反应