Java Spring MVC/Spring Boot 项目实现图片或文件下载,该方法同样适用于struts1/2环境或者普通Java Web项目环境。下载源码参考:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.xql.test.common.IOUtil;
@Controller
public class TestController {
@RequestMapping(value = "test/fileDownload")
//测试
@RequestMapping(value = "test/fileDownload")
public void fileDownload(HttpServletResponse response) {
// 图片流
InputStream imgInputStream = null;
// 输出流
OutputStream os = null;
try {
// 1.从网络中读取到一张图片
// 创建URL对象[这里引用的百度logo的图片地址]
String imageUrl = "https://www.baidu.com/img/bd_logo1.png";
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
// 获取图片输入流
imgInputStream = conn.getInputStream();
// 2.将inputstream流转换为byte[]/数据
byte[] imgBytes = IOUtil.inputStream2byte(imgInputStream);
// 3.获得response中的输出流
os = response.getOutputStream();
// 4.设置输出的一些参数
// 4.1设置输出文件名
String fileName = imageUrl.substring(imageUrl.lastIndexOf("/"),
imageUrl.length());
response.setHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\"");
// 4.2设置下载页面文件显示大小
response.addHeader("Content-Length", "" + imgBytes.length);
// 4.3设置content类型
response.setContentType("application/octet-stream;charset=UTF-8");
// 5.将图片输出
os.write(imgBytes);
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
// 6.无论成功与否关闭相应的流
try {
if (imgInputStream != null) {
imgInputStream.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
}
注意事项
①IOUtil.inputStream2byte(InputStream is) 工具类,将inputstream 转换为byte数组
②获取的response是来自于HttpServletResponse
http://blog.xqlee.com/article/11.html