Подтвердить что ты не робот

Загрузить файл с оригинальным именем файла

В моем проекте я загружаю файл. При загрузке я сохраняю исходное имя файла и расширение в базе данных и сохраняю этот файл с некоторым GUID на сервере, сгенерированный GUID также сохраняется в базе данных вместе с именем файла и расширением.

Например,

- Имя файла для загрузки - questions.docx

-Тогда orignalFileName будет "вопросами"

-FileExtension будет ".docx"

-Файл будет загружен с именем файла как "0c1b96d3-af54-40d1-814d-b863b7528b1c"

Загрузка работает нормально... но когда я загружаю какой-то файл, он загружается с именем файла как GUID в вышеприведенном случае, его "0c1b96d3-af54-40d1-814d-b863b7528b1c".
Как загрузить файл с его исходным именем файла, т.е. "questions.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();
        }
    }

Является ли этот код идеальным?

4b9b3361

Ответ 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 + "\"");
}

Ответ 3

Вы можете установить имя файла в заголовке.

Скажем, что вы используете RestFul Webservice, тогда ResponseBuilder можно использовать следующим образом:

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

Тип содержимого и имя файла оба могут быть/установлены во время выполнения.

Ответ 4

Привет @Amogh Используйте ниже код

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

Ответ 5

Чтобы назвать файл с текущей датой в заголовке ответа, вы можете использовать следующий код:

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 может быть любым форматом даты, который вы хотите!:)

enter code here

Ответ 6

Кодировать Content-Disposition в соответствии с RFC 5987

Этот код может обрабатывать символ не ASCII. Часть кода копируется из 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://tools.ietf.org/html/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://tools.ietf.org/html/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 == '~';
    }
}

Ответ 7

С помощью этой строки в заголовке вы можете установить имя файла:

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