在我的项目中,我正在上传文件.在上传时,我将其原始文件名和扩展名保存在数据库中,并将该文件保存GUID在服务器上,生成的GUID也与文件名和扩展名一起存储在数据库中.
例如-
- 上传的文件名是questions.docx
- 然后orignalFileName将是"问题"
-FileExtension将是".docx"
-File上传文件名为"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();
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码是完美的吗?
Hun*_*hao 50
您应该将原始文件名设置为响应标头,如下所示:
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);
Run Code Online (Sandbox Code Playgroud)
希望能帮到你:)
您只需从数据库中获取originalName并将其设置在Content-Disposition标头中:
@RequestMapping("/../download")
public ... download(..., HttpServletResponse response) {
...
response.setHeader("Content-Disposition", "attachment; filename=\"" + original + "\"");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55446 次 |
| 最近记录: |