“attachment; filename=“不生效问题解决

背景

        在文件下载时,明明在响应头里加了"attachment; filename="却没有生效,伪代码如下:

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
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.RestController;

import java.io.File;
import java.io.IOException;

@RestController
public class FileController {

    @GetMapping("/download/{innerFilename}/{downloadFilename}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String innerFilename, @PathVariable String downloadFilename) throws IOException {
        // 加载文件
        byte[] fileContent = loadFileContent(innerFilename);

        // 包装fileContent
        ByteArrayResource resource = new ByteArrayResource(fileContent);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadFilename + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    // 加载文件
    private byte[] loadFileContent(String innerFilename) throws IOException {
        // 读取文件
        File file = new File("path/to/your/files/" + innerFilename);
        return FileUtils.readFileToByteArray(file);
    }
}

解决方案 

  1. 浏览器缓存的原因。有些浏览器会在下载同一文件名的文件时使用缓存,而不会考虑新的 Content-Disposition 头。你可以尝试使用不同的浏览器或者清除浏览器缓存来检查是否仍然存在问题。
  2. 确保你的文件名没有特殊字符空格,以防止可能引起问题的字符。
  3. 如果问题仍然存在,可能需要考虑其他方法,比如在文件名中添加时间戳或随机字符串来确保唯一性。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值