oss文件下载

@RequestMapping(value = "/downFile")
	@ResponseBody
	public void downFile(HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream input = null;
		OutputStream outputStream = null;
		try {
            String filePath = request.getParameter("path");
            filePath = filePath.replaceAll("\\\\", "/");
            String fileName = getName(filePath);

            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),"ISO8859-1"));
            // endpoint,accessKeyId,accessKeySecret,bucketName是oss自带参数,登陆oss查看,或者给公司要,fileName是文件上传到oss后的文件名
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            OSSObject object = ossClient.getObject(bucketName, fileName);
            input = new BufferedInputStream(object.getObjectContent());
            byte[] buffBytes = new byte[1024];        
            outputStream = response.getOutputStream();          
            int read = 0;
            while ((read = input.read(buffBytes)) != -1) {
                 outputStream.write(buffBytes, 0, read);
            }     
            outputStream.flush();
            ossClient.shutdown();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
            	if (outputStream != null) {
            		outputStream.close();
            	}
            	if (input != null) {
            		input.close();
            	}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}
	
	// 获取添加后的文件名称
	public String getName(String filepath) {
		if (!filepath.equals(null)) {
			if (filepath.contains("/")) {
				return filepath.substring(filepath.lastIndexOf("/") + 1);
			}
		}
		return "";
	}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中实现OSS文件下载,你可以按照以下步骤进行操作: 1. 首先,你需要引入阿里云OSS的Java SDK依赖。在你的`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.9.2</version> </dependency> ``` 2. 在Spring Boot的配置文件中,添加OSS相关的配置项,包括`accessKey`、`secretKey`、`endpoint`和`bucketName`等信息。 ```properties # OSS配置 spring.aliyun.oss.access-key=your-access-key spring.aliyun.oss.secret-key=your-secret-key spring.aliyun.oss.endpoint=your-endpoint spring.aliyun.oss.bucket-name=your-bucket-name ``` 3. 创建一个用于处理文件下载的Controller。在该Controller中,注入`AliyunOSSClient`对象,并实现一个下载文件的接口。 ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.GetObjectRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.InputStream; import java.net.URLEncoder; @RestController @RequestMapping("/files") public class FileController { @Autowired private OSS ossClient; @Value("${spring.aliyun.oss.bucket-name}") private String bucketName; @GetMapping("/{fileName}") public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String fileName) throws Exception { // 构造OSS文件下载请求 GetObjectRequest request = new GetObjectRequest(bucketName, fileName); // 下载文件流 InputStream inputStream = ossClient.getObject(request).getObjectContent(); // 设置文件下载响应头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8")); // 返回文件下载响应 return ResponseEntity .ok() .headers(headers) .body(new InputStreamResource(inputStream)); } } ``` 在上述代码中,`/{fileName}`表示下载文件的URL路径,`fileName`是要下载的文件名。 注意:上述代码中的`ossClient`对象需要通过Spring Bean配置来创建,并且需要在应用启动时初始化。 4. 配置OSS客户端的Bean。在你的Spring Boot应用的配置类中,添加以下内容: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OSSConfig { @Value("${spring.aliyun.oss.endpoint}") private String endpoint; @Value("${spring.aliyun.oss.access-key}") private String accessKey; @Value("${spring.aliyun.oss.secret-key}") private String secretKey; @Bean public OSS ossClient() { return new OSSClientBuilder().build(endpoint, accessKey, secretKey); } } ``` 在上述配置类中,通过`@Value`注解获取配置文件中的OSS相关配置项,然后创建并返回一个`OSS`对象。 这样,当访问`/files/{fileName}`接口时,就会触发文件下载操作。 需要注意的是,上述代码中的配置项需要根据你自己的阿里云OSS账号进行相应的配置。另外,还需要确保你的Spring Boot应用能够访问到正确的OSS服务。 希望以上信息能够帮助到你实现Spring Boot中的OSS文件下载功能!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值