简体   繁体   中英

How I fixed: Can't upload images using formData (Browser Compatibilty)

Can't use FormData on iOS, but in all Desktop browsers including Safari work.

 $("#form").on('submit', function(e){ let formData = new FormData(this); sendwithAjax(formData); }); 

I had a couple of problems with FormData due to this:

 $("#form").on('submit', function(e){ let formData = new FormData(this); sendwithAjax(formData); }); 

Most browsers support this. The variable 'this' or 'e.currentTarget' corresponds to the form which contain all the inputs. So we just do a formData of a form.

Well, when it came to mobile, iOS, to be more specific things didn't go well. The XHR requests just crashed.

This is how I fixed:

 var formData = new FormData(); for (var i = 0; i < form.length; i++) { var element = form[i]; if(element.type === "file" && element.files.length > 0){ formData.append(element.name, element.files[0], element.files[0].name); } else if(element.type === "checkbox" && element.checked){ formData.append(element.name, element.value); } else if(element.type !== "checkbox"){ formData.append(element.name, element.value); } } sendWithAjax(formData) 

The problem was the 'form' inside the FormData instance, so I put every element of the form manually and it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM