简体   繁体   中英

How to manipulate form file input before POST

I have a form which includes an input type="file" to upload an image, and I want to be able to manipulate that image before submission.

(I may want to crop or resize it using an existing jQuery library, for example. I'm posting to WordPress and am tied to gravity forms, which means I can't use a plug-in such as jQuery-file-upload which includes server-side handling too, so my question is more generic.)

I'm trying to understand what happens on submit and how the browser constructs the post to be handled by the server.

If a user has selected a file, can I take that file and do something with it in javascript, and then on the form submit have the browser take my amended version from memory rather than the original version linked to in the input field?

[EDIT]

So, I've discovered some useful insights. Anyone looking at this, here is a useful thread here on SO.

When a user selects an image on a file input field, I can use html5 canvas to manipulate it. I need to then convert it back to a binary file to upload (via canvas.toBlob() in the most modern browsers, or using the technique mentioned in the above link for older browsers).

Then what do I do with it? I can POST it via Ajax as per this Mozilla developers article and for most people this will be fine.

My problem is that I am tied to using Gravity Forms and I need to let it handle the form submission.

Which means I need to manipulate my existing form and let the user hit the submit button as normal.

Where my form has

<input type="file" name="input_3" id="input_3_3">

I have tried in JavaScript:

document.getElementbyId('input_3_3').value = myBlob;

but it appears that I can't assign the blob to the input field.

Reading around, the solutions which involve Ajax make use of FormData objects, and I thought I might be able to append the field but that doesn't seem to work (the form on the page in the DOM and the FormData object are not the same thing?).

So, that's where I'm stuck.

从理论上讲,您可以使用blob,但实际上并不是一个好的解决方案,因为并非所有浏览器都支持blob,并且当前没有javascripts库可以处理图像,因此最好的选择是将其发送给服务器并让服务器对其进行处理。

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