简体   繁体   English

使用原始文件名下载文件

[英]Download file with original file name

In my project I am uploading a file.在我的项目中,我正在上传一个文件。 While uploading, I am saving its original file name and extension in a database and saving that file with some GUID on server, generated GUID is also stored in database along with file name and extension.上传时,我将其原始文件名和扩展名保存在数据库中,并将该文件与一些GUID一起保存在服务器上,生成的 GUID 也与文件名和扩展名一起存储在数据库中。

For example-例如-

-File name for uploading is questions.docx -上传文件名为questions.docx

-Then orignalFileName will be "questions" - 然后 orignalFileName 将是“问题”

-FileExtension will be ".docx" -文件扩展名为“.docx”

-File be get uploaded with file name as "0c1b96d3-af54-40d1-814d-b863b7528b1c" -文件被上传,文件名为“0c1b96d3-af54-40d1-814d-b863b7528b1c”

Uploading is working fine..but when I am downloading some file it gets downloaded with file name as the GUID in above case its "0c1b96d3-af54-40d1-814d-b863b7528b1c".上传工作正常..但是当我下载一些文件时,它会以文件名作为 GUID 下载,在上面的例子中是“0c1b96d3-af54-40d1-814d-b863b7528b1c”。
How can I download a file with its original file name ie "questions.docx".如何下载原始文件名为“questions.docx”的文件。

Code Added添加代码

    /**
     * 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();
        }
    }

Is this code is perfect?这段代码是完美的吗?

You should set your origin file name into the response header, like below:您应该将原始文件名设置到响应标头中,如下所示:

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);

Hope to help you:)希望能帮到你:)

You just fetch the originalName from the database and set it in the Content-Disposition header:您只需从数据库中获取 originalName 并将其设置在Content-Disposition标头中:

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

You can set the file name in the header.您可以在标题中设置文件名。

Say for Example you are using RestFul Webservice then ResponseBuilder can be used like this:例如,您使用的是 RestFul Webservice,那么ResponseBuilder可以这样使用:

ResponseBuilder rsp = Response.ok("Your Content Here", "application/docx");    
rsp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

The content type and file name both are/can be set at run time.内容类型和文件名都是/可以在运行时设置。

嗨@Amogh 使用下面的代码

response.setHeader("Content-Disposition", "attachment; filename="+FILENAME+".docx");

To name a file with current Date in response header you can use following code:要在响应标头中使用当前日期命名文件,您可以使用以下代码:

final String Date_FORMAT = "dd/MM/yyyy"; 
Date currentDate = new Date();
SimpleDateFormat formatDate = new SimpleDateFormat(Date_FORMAT);
String datenew = formatDate.format(currentDate);

response.setContentType("application/pdf");//for pdf file
response.setHeader("Content-disposition","attachment;filename="+ datenew +"Smoelenboek.pdf");

Date_Format can be any date format you want!! Date_Format 可以是您想要的任何日期格式!! :) :)

enter code here

Encode Content-Disposition according to RFC 5987根据RFC 5987编码内容处理

This code can handle non ASCII character.此代码可以处理非 ASCII 字符。 Some part of the code is copied from Spring Framework.部分代码是从 Spring Framework 复制的。

import java.nio.charset.Charset;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Assert;

public class HttpHeadersExtended extends HttpHeaders {

    public static final String CONTENT_DISPOSITION_INLINE = "inline";
    public static final String CONTENT_DISPOSITION_ATTACHMENT = "attachment";

    /**
     * Set the (new) value of the {@code Content-Disposition} header
     * for {@code main body}, optionally encoding the filename using the RFC 5987.
     * <p>Only the US-ASCII, UTF-8 and ISO-8859-1 charsets are supported.
     *
     * @param type content disposition type
     * @param filename the filename (may be {@code null})
     * @param charset the charset used for the filename (may be {@code null})
     * @see <a href="https://www.rfc-editor.org/rfc/rfc7230#section-3.2.4">RFC 7230 Section 3.2.4</a>
     * @since 4.3.3
     */
    public void setContentDisposition(String type, String filename, Charset charset) {

        if (!CONTENT_DISPOSITION_INLINE.equals(type) && !CONTENT_DISPOSITION_ATTACHMENT.equals(type)) {
            throw new IllegalArgumentException("type must be inline or attachment");
        }

        StringBuilder builder = new StringBuilder(type);
        if (filename != null) {
            builder.append("; ");

            if (charset == null || charset.name().equals("US-ASCII")) {
                builder.append("filename=\"");
                builder.append(filename).append('\"');
            } else {
                builder.append("filename*=");
                builder.append(encodeHeaderFieldParam(filename, charset));
            }
        }
        set(CONTENT_DISPOSITION, builder.toString());
    }
    
    /**
     * Copied from Spring  {@link org.springframework.http.HttpHeaders}
     *
     * Encode the given header field param as describe in RFC 5987.
     *
     * @param input the header field param
     * @param charset the charset of the header field param string
     * @return the encoded header field param
     * @see <a href="https://www.rfc-editor.org/rfc/rfc5987">RFC 5987</a>
     */
    private static String encodeHeaderFieldParam(String input, Charset charset) {
        Assert.notNull(input, "Input String should not be null");
        Assert.notNull(charset, "Charset should not be null");
        if (charset.name().equals("US-ASCII")) {
            return input;
        }
        Assert.isTrue(charset.name().equals("UTF-8") || charset.name().equals("ISO-8859-1"),
            "Charset should be UTF-8 or ISO-8859-1");
        byte[] source = input.getBytes(charset);
        int len = source.length;
        StringBuilder sb = new StringBuilder(len << 1);
        sb.append(charset.name());
        sb.append("''");
        for (byte b : source) {
            if (isRFC5987AttrChar(b)) {
                sb.append((char) b);
            } else {
                sb.append('%');
                char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
                char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
                sb.append(hex1);
                sb.append(hex2);
            }
        }
        return sb.toString();
    }

    /**
     * Copied from Spring  {@link org.springframework.http.HttpHeaders}
     */
    private static boolean isRFC5987AttrChar(byte c) {
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
            c == '!' || c == '#' || c == '$' || c == '&' || c == '+' || c == '-' ||
            c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
    }
}

使用标题中的这一行,您可以设置文件的名称:

response.setHeader("Content-disposition", "attachment; filename="+ fileName);

You can also use the ContentDisposition builder to add to an HttpHeaders instance.您还可以使用 ContentDisposition 构建器添加到 HttpHeaders 实例。

Example Code示例代码

InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentDisposition(
                    ContentDisposition.builder("attachment")
                                      .filename(file.getName()).build());
            return ResponseEntity.ok()
                                 .contentLength(file.length())
                                 .contentType(MediaType.APPLICATION_OCTET_STREAM)
                                 .headers(httpHeaders)
                                 .body(resource);

Sometimes you need to handle the encoding problem:有时你需要处理编码问题:

response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM