下载具有原始文件名的文件 [英] Download file with original file name
问题描述
在我的项目中,我正在上传文件.上传时,我将其原始文件名和扩展名保存在数据库中,并使用服务器上的某些 GUID
保存该文件,生成的GUID以及文件名和扩展名也存储在数据库中.
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.
例如-
-要上传的文件名是questions.docx
-File name for uploading is questions.docx
-然后orignalFileName将是问题"
-Then orignalFileName will be "questions"
-FileExtension将为".docx"
-FileExtension will be ".docx"
-以文件名"0c1b96d3-af54-40d1-814d-b863b7528b1c"上传文件
-File be get uploaded with file name as "0c1b96d3-af54-40d1-814d-b863b7528b1c"
上传工作正常..但是当我下载某些文件时,它以GUID文件名下载,在上述情况下,其名称为"0c1b96d3-af54-40d1-814d-b863b7528b1c".
如何下载文件其原始文件名为"questions.docx".
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".
How can I download a file with its original file name i.e "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();
}
}
此代码是否完美?
推荐答案
您应将原始文件名设置为响应标头,如下所示:
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:)
这篇关于下载具有原始文件名的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!