Is it possible to add the file extension into the HTTP header?
I have developed a program for sending a file using an API call. The file will not be restricted to .doc or .pdf, it can be with .exe or .zip extension as well.
The file is successfully uploaded to the server but the file extension seems not correct, it's showing the file type as data, while I'm expecting another file type.
Here down the sample code sources for the upload part:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://ServerName:Port/Anything/data"); //remote API URL
String filepath = "C://User//test//";
String file1 = filepath.concat(file);
System.out.println("Sending the file");
FileBody bin = new FileBody(new File(file1)); // take the file from directory
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("display_name", (ContentBody) bin)
.build();
post.addHeader("filename", file1);
post.setEntity(reqEntity); // send via post method
Will the FileBody read the file extension as well?
Extract the Content-Disposition header from the headers list using (HttpServletRequest) request.getHeader("Content-Disposition"). This will have the filename present in last as Content-Disposition: form-data; name="uploadedfile"; filename="file.ext".
From here you can extract the file type.
You can do it in way also:
String fileName = uploadedFile.getFileName();
String mimeType = getServletContext().getMimeType(fileName);
if (mimeType.startsWith("text/")) {
// It's a text.
}else if(mimeType.startsWith("image/")){
// It's an image.
}
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With