LGAP
LGAP

Reputation: 2473

Validation to check whether its a ".txt" file

I have this particular piece of code for restricting the users to upload image files only.

  if (!fileName.getContentType().startsWith("image/")) 
  errors.add("", new ActionError("errors.imageFile.contentType"));

Similary I want the users to upload only files with extension ".txt" in another scenario. What MIME type should I use or please let me know the code which will be helpful for achieving this task.

Upvotes: 2

Views: 1105

Answers (4)

Stephen C
Stephen C

Reputation: 719551

I want the users to upload only files with extension ".txt" in another scenario.

The mime type for plain text files is "text/plain". Or you can check the name of the uploaded file.

However, these won't prevent users uploading non-text files. All they need to do (on Windows) is to rename a non-text file to have the ".txt" extension ... and then upload it.

If you really want to make sure that users only upload text, you need to test the files after they have been uploaded.

Upvotes: 1

npinti
npinti

Reputation: 52185

Text files have the following MIME type:

text/plain

However, according to this site, it is not the only one. You can use Apache's FileNameUtils getExtension method to get the extension of the file.

Upvotes: 2

Andrew Thompson
Andrew Thompson

Reputation: 168845

What MIME type should I use ..?

Content-Type: text/plain

Upvotes: 1

AlexR
AlexR

Reputation: 115388

Typically the mime type for text files is text/plain

Upvotes: 2

Related Questions