Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP header parameter for File extension in API call

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?

like image 901
attack Avatar asked Dec 04 '25 16:12

attack


1 Answers

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.

like image 195
SachinSarawgi Avatar answered Dec 06 '25 06:12

SachinSarawgi