File type - blank line when loading from native Android browser

I have input(type="file") on a web page.

 <input type='file' name="file" accept="image/*" /> 

I use jQuery to capture the file as follows:

 $('input').on('change', function(e) { console.log(e.target.files[0]); }); 

I need to check if e.target.files[0].type pattern "image.*" , So I do: var matches = e.target.files[0].type.match('image.*');

This works fine in most cases, but when the application launches from its own Android browser, e.target.files[0].type is an empty string. This happens if I select an image stored on the device. If I take an image with the camera e.target.files[0].type , this is "image/jpeg" .

Has anyone encountered this problem before?

+6
source share
1 answer

As I added a comment, I tried to use use cases with the following code snippet:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Image Test</title> </head> <body> <form method="POST" enctype="multipart/form-data"> <input type="file" accept="image/*" onchange="previewAndUploadFile(event)"/><br/> <img id="imagePreview" width="200" height="200"/> <div id="imageType"></div> </form> <script type="text/javascript"> function previewAndUploadFile(event) { var type = document.getElementById("imageType"); var file = event.target.files[0]; try { var reader = new FileReader() reader.onload = function() { var preview = document.getElementById("imagePreview"); preview.src = reader.result; } reader.readAsDataURL(file); type.innerHTML = file.type; } catch(e){ type.innerHTML = "Invalid image."; } } </script> </body> </html> 
  • When the file name is sample.jpeg and the image is a valid image, everything works fine. The result is image/jpeg

  • When the file name is sample (the file extension is deleted, but the contents of the image remain valid), the result was empty.

  • When the image is damaged (editing it in notepad, you can try other ways), and the file name is sample.jpeg , the image type was still specified as image/jpeg .

  • Repeating case-3 with the image renamed to sample , the image type appears again as an empty string.

Maybe your case was one of them.

0
source

Source: https://habr.com/ru/post/975364/


All Articles