ajax file upload

走远了吗. 提交于 2019-11-30 19:10:00

问题


I am struggling to get a file uploaded, processed and displayed without reloading the page. What do I use for jquery to get the file posted to the server properly?

 <html>

 <body>

 <form action="upload.php" method="post" enctype="multipart/form-data" id="uploadform">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" /> 
  <br />
  <input type="submit" id="submit" />
  </form>

  </body>
  </html>

回答1:


You can do it by putting the upload form in an iframe and communicating between the main window and the frame with javascript. It's ugly but it's the only way to do it in some browsers.

jQuery File Upload is an awesome plugin that incorporates async XHR uploads and falls back on an iframe for browsers that are not capable. It also supports drag and drop (for capable browsers) out of the box. It's not the simplest plug-in in the world to use, but well worth the effort, it covers all the bases.




回答2:


Using vanilla HTML, it is impossible to upload a file over an AJAX request. Take a look at something along the lines of SWFUpload. You can upload multiple files, specify wildcard filters for file section, and have the ability to display progress bars and other status information during the upload.




回答3:


You can upload a form containing INPUT[type="file"] without reloading the page by using jquery.upload.js. In the $.Deferred.done handler you can add your own code to display the server response.

$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
    if( progressEvent.lengthComputable) {
        var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
        if( upload) {
            console.log( percent + ' uploaded');
        } else {
            console.log( percent + ' downloaded');
        }
    }
})
.done( function( data) {
    console.log( 'Finished upload');

    // add your code for rendering the server response
    // into html here
});

You can get it here : https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/public/lib/ampere/jquery.upload.js



来源:https://stackoverflow.com/questions/6541155/ajax-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!