使用原始文件名下载文件

2022-09-01 05:42:37

在我的项目中,我正在上传一个文件。上传时,我将其原始文件名和扩展名保存在数据库中,并将该文件与服务器上的一些文件一起保存,生成的GUID也与文件名和扩展名一起存储在数据库中。GUID

例如——

-上传的文件名是问题.docx

- 那么原始文件名将是“问题”

-文件扩展将是“.docx”

-文件上传文件名为“0c1b96d3-af54-40d1-814d-b863b7528b1c”

上传工作正常..但是当我下载一些文件时,它会在上面的情况下下载文件名作为GUID的“0c1b96d3-af54-40d1-814d-b863b7528b1c”。
如何下载具有原始文件名的文件,即“问题.docx”。

已添加代码

    /**
     * code to display files on browser
     */
    File file = null;
    FileInputStream fis = null;
    ByteArrayOutputStream bos = null;

    try {
        /**
         * C://DocumentLibrary// path of evidence library
         */
        String fileName = URLEncoder.encode(fileRepo.getRname(), "UTF-8");
        fileName = URLDecoder.decode(fileName, "ISO8859_1");
        response.setContentType("application/x-msdownload");            
        response.setHeader("Content-disposition", "attachment; filename="+ fileName);
        String newfilepath = "C://DocumentLibrary//" + systemFileName;
        file = new File(newfilepath);
        fis = new FileInputStream(file);
        bos = new ByteArrayOutputStream();
        int readNum;
        byte[] buf = new byte[1024];
        try {

            for (; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
        } catch (IOException ex) {

        }
        ServletOutputStream out = response.getOutputStream();
        bos.writeTo(out);
    } catch (Exception e) {
        // TODO: handle exception
    } finally {
        if (file != null) {
            file = null;
        }
        if (fis != null) {
            fis.close();
        }
        if (bos.size() <= 0) {
            bos.flush();
            bos.close();
        }
    }

这段代码是完美的吗?


答案 1

您应该将源文件名设置到响应标头中,如下所示:

String fileName = URLEncoder.encode(tchCeResource.getRname(), "UTF-8");
fileName = URLDecoder.decode(fileName, "ISO8859_1");
response.setContentType("application/x-msdownload");            
response.setHeader("Content-disposition", "attachment; filename="+ fileName);

希望能帮到你:)


答案 2

您只需从数据库中获取原始名称并将其设置在标头中:Content-Disposition

@RequestMapping("/../download")
public ... download(..., HttpServletResponse response) {
  ...
  response.setHeader("Content-Disposition", "attachment; filename=\"" + original + "\"");
}

推荐