4

I created one web page where i want to upload only text file using JavaScript and it is working fine.

Using below JavaScript, it is checking upload file is txt or not?

<script>
  function checkExt() {
    if(document.mainForm.myfile.value.lastIndexOf(".txt")==-1) {
      alert("Please upload only .txt extention file");
      return false;
    }
  }
</script>

<form name="mainForm">
   <input type="file" name="myfile" onchange="checkExt();"/>
</form>

Live Demo Here

Problem: If I change extension of file .exe to .txt manually then it is also being upload because i'm checking file's extension only. So My question is how to protect from exe file (which is Manually changed to txt) to upload.

I want to stop upload exe, jar files which is changed or renamed forcefully or manually.

RGI
  • 161
  • 1
  • 10
  • Javascript can be changed by the client. So this will only save you from some script kids. The one who can really hurt you will just laugh about any js solution. You need a backend verification. – Doomenik Aug 16 '17 at 11:25
  • @Doomenik, Okay, I'll search on google for backend verification or Can you refer any link of this scenario using Java??? – RGI Aug 16 '17 at 11:31
  • https://stackoverflow.com/questions/4169713/how-to-check-a-uploaded-file-whether-it-is-a-image-or-other-file – Doomenik Aug 16 '17 at 11:45

3 Answers3

2

You need to verify modified exe file to txt on backend code. It is very simple code. Below program is checking file is executable or not either exe file changed to .txt extension.

Here we can read file for verification means file is contain bytes code or not

import java.io.File;
import java.io.FileInputStream;

public class TestExecutableFile {

    public static void main(String[] args) {

        byte[] firstBytes = new byte[4];
        try {
            FileInputStream input = new FileInputStream(new File("[filepath]/[filename]"));
            input.read(firstBytes);

            // Checking file is executable
            if (firstBytes[0] == 0x4d && firstBytes[1] == 0x5a) {
                System.out.println("Executable File");
            }else{
                System.out.println("Non Executable File");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Piyush Gupta
  • 2,181
  • 3
  • 13
  • 28
0

In my opinion client side validation on extension will not serve the purpose, you need to do MIME type validation on server side can solve the problem better.

Ref. article Using .NET, how can you find the mime type of a file based on the file signature not the extension

by ROFLwTIME

0

You just need to get file not with form.value but with form.files. There you can find such properties of file:

{
    lastModified: 1502265800000
    lastModifiedDate: Wed Aug 09 2017 11:03:20 GMT+0300 (EEST) {}
    name: "14ecdf0302f4bbc84cfbbf85b3b94013.jpg"
    size: 463225
    type: "image/jpeg"
}