图片从oss下载

本文介绍了一个基于阿里云OSS的文件下载控制器的具体实现,该控制器能够处理来自不同浏览器的请求,通过OSSClient获取文件并以流形式返回给客户端,支持文件名的编码处理以确保跨浏览器兼容性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.zjxnjz.mall.modular.download.controller;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.aliyun.oss.OSSClient;
import com.zjxnjz.mall.core.util.OssClientFactory;

/**
 * 
 * @author ljj 文件下载
 *
 */
@Controller
@RequestMapping("/download")
public class DownLoadController {

	/**
	 * 模板下载
	 * 
	 * @param name
	 */
	@GetMapping(value = "/filedownload")
	public void fileDownLoad(@RequestParam(value = "ossUrl", required = true) String ossUrl,
			HttpServletResponse response, HttpServletRequest request) {
		try {
			String fileName = ossUrl.substring(ossUrl.lastIndexOf("/")+1);
			OSSClient client = OssClientFactory.getOssClient();
			InputStream inputStream = client
					.getObject(OssClientFactory.bucketName, OssClientFactory.getOssUrlKey(ossUrl)).getObjectContent();
			String userAgent = request.getHeader("USER-AGENT");
			if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} else {
				fileName = URLEncoder.encode(fileName, "UTF-8");// 其他浏览器
			}
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(inputStream);
			// 清空response
			response.reset();
			// 设置response的Header
			response.setCharacterEncoding("UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			//以下代码图片下载时 必须注掉 否则会导致图片失真
			/* response.addHeader("Content-Length", "" + fis.available()); */
			response.setContentType("application/octet-stream");
			int len = 0;
			byte[] buffer = new byte[1024];
			OutputStream out = response.getOutputStream();
			while ((len = fis.read(buffer)) > 0) {
				// 将缓冲区的数据输出到客户端浏览器
				out.write(buffer, 0, len);
			}
			fis.close();
			out.flush();
			out.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值