Java web项目下载图片/文件

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(22)   2023-03-28 11:29:14
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

 
标签:
地址:https://www.leftso.com/article/11.html

相关阅读

java WEB中Cookie的操作和使用,java,cookie,web
Java编程中处理图片文件与base64串的图片相互转化工具类,方便在编程中处理前端传递过来的base64图片。
功能说明:1.指定图片大小缩放图片(reSize);2.指定图片的宽度,高度根据比例缩放(reSizeByWith);3.指定图片的高度,宽度根据比例缩放(reSizeByHeight);4.判...
java 图片 无损压缩。随着科技进步,大家手机拍的照片也从之前的几百KB变成几MB或者10MB了,有些情况我们需要压缩一下图片节省网络资源。这里将会讲解如何采用Java语音进行图片的无损压缩
SpringBoot使用@ResponseBody返回图片的实现以前使用HttpServletResponse可以通过输出流的方式来向前台输出图片
Spring mvc文件下载IE/Edge中文乱码解决,在spring mvc项目开发中,我们可能经常遇到文件的上传和下载操作。这里将讲解在IE/Edge浏览器中文件下载中文乱码的解决方法。
Java编程中,很多报表系统需要导出Excel文件,并且某些时候需要导出一定的图形统计,其实就是将图片放在Excel中,下面讲解Java如何实现Excel图片编辑插入
Java编程之通过eclipse创建maven自定义项目原型模板(Archetype),Java编程,maven自定义项目模板
问题描述Java 开发中使用spring  boot 下载excel文件提示“文件中部分内容有问题