java web图片_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());

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值