开发者

showing image loaded from file before upload/POST

I have the following html code to upload an image:

<input type="file" name="before"  size="40">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">

and I want to show the image that the user uploads before it's actually processed in the backend. How do I do this开发者_开发知识库?

Basically what I want to do is to upload an image from an image in your computer and show it so it can be cropped using jCrop and then process the image in the backend


  • Save the file on post back like normal
  • During postback
    • Add link to image on page
    • Add javascript to 'onload' that calls another page to handle processing of image


What you need is HTML5 File API. Take a look at readAsDataURL.

Basically, you'll need to catch the onchange event on your input[type="file"] and load the associated file with FileReader, then save the image content in an <img href="data" />. More clear informations here.


I don't think you are going to get around not doing some processing on the server since you are not going to be able to see the file you are uploading until you submit. You can try to do something via Ajax though. I came across the jQuery Form Plugin and the File Uploads example.

Copy and pasted from the site:

Since it is not possible to upload files using the browser's XMLHttpRequest object, the Form Plugin uses a hidden iframe element to help with the task. This is a common technique, but it has inherent limitations. The iframe element is used as the target of the form's submit operation which means that the server response is written to the iframe. This is fine if the response type is HTML or XML, but doesn't work as well if the response type is script or JSON, both of which often contain characters that need to be repesented using entity references when found in HTML markup.

To account for the challenges of script and JSON responses, the Form Plugin allows these responses to be embedded in a textarea element and it is recommended that you do so for these response types when used in conjuction with file uploads. Please note, however, that if there is no file input in the form then the request uses normal XHR to submit the form (not an iframe). This puts the burden on your server code to know when to use a textarea and when not to. If you like, you can use the iframe option of the plugin to force it to always use an iframe mode and then your server can always embed the response in a textarea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜