Jama A.
Jama A.

Reputation: 16089

Content-type is not as expected when uploading an excel file

I have this code:

 <h:form id="form" enctype="multipart/form-data">
     <t:inputFileUpload id="eFile" value="#{Parser.uploadFile}" storage="file"/>
     <t:commandButton value="Parse" action="#{Parser.parse}"/>
  </h:form>

And in my Parser class:

public class Parser {

    public Parser() {

    }

    public String parse() {
        //it should be 'application/vnd.ms-excel' type 
        //since i'm uploading an excel file saved in MS Excel 2007
        System.err.print(uploadFile.getContentType());
        // but its content-type is 'application/octet-stream'
        return null;

    }

    public UploadedFile getUploadFile() {
        return uploadFile;
    }

    public void setUploadFile(UploadedFile uploadFile) {
        this.uploadFile = uploadFile;
    }
}

In my project everywhere excel files are checked depending on its content-type, they worked fine some time ago, but now I couldn't understand why they are not working properly.

Upvotes: 1

Views: 4305

Answers (1)

BalusC
BalusC

Reputation: 1108782

It's a client side matter. The UploadedFile#getContentType() returns whatever the client has sent in the Content-Type header field of the multipart/form-data part. Apparently the client in question does not have any mime type associated with the file extension of the uploaded file. That can happen if the client does not have MS Excel installed.

You, as being the server, can also determine the mime type based on the file extension by ExternalContext#getMimeType(), or when you're still on the ancient JSF 1.x, by ServletContext#getMimeType().

String filename = FilenameUtils.getName(uploadedFile.getName()); // This is available by Commons IO which you should already have.
String mimetype = FacesContext.getCurrentInstance().getExternalContext().getMimeType(filename);
// ...

The mime type information is obtained from <mime-mapping> entries in web.xml. The servletcontainer has a whole list in its own default web.xml (in case of for example Tomcat, you can find it in its /conf folder). You can extend/override it in your webapp's own web.xml like as follows for XLSX:

<mime-mapping>
    <extension>xlsx</extension>
    <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>

Note that this detection is purely based on file extension, not on file content. This does thus not prevent incorrect detection when the client has edited the file extension. Most reliable would be to parse it using a real Excel file parser like Apache POI or JExcelAPI and check if it doesn't throw some exception while parsing.

Upvotes: 2

Related Questions