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.
For example-
-File name for uploading is questions.docx
-Then orignalFileName will be "questions"
-FileExtension will be ".docx"
-File be get uploaded with file name as "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".
How can I download a file with its original file name i.e "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 just fetch the originalName from the database and set it in the
Content-Disposition
header:You should set your origin file name into the response header, like below:
Hope to help you:)
Encode Content-Disposition according to RFC 5987
This code can handle non ASCII character. Some part of the code is copied from Spring Framework.
With this line in the header, you can set the name of the file:
You can set the file name in the header.
Say for Example you are using RestFul Webservice then ResponseBuilder can be used like this:
The content type and file name both are/can be set at run time.
To name a file with current Date in response header you can use following code:
Date_Format can be any date format you want!! :)