[removed] Upload file

2019-01-01 00:44发布

Let's say I have this element on the page:

<input id="image-file" type="file" />

This will create a button that allows the users of the web page to select a file via an OS "File open..." dialog in the browser.

Let's say the user clicks said button, selects a file in the dialog, then clicks the "Ok" button to close the dialog.

The selected file name is now stored in:

document.getElementById("image-file").value

Now, let's say that the server handles multi-part POSTs at the URL "/upload/image".

How do I send the file to "/upload/image"?

Also, how do I listen for notification that the file is finished uploading?

4条回答
看风景的人
2楼-- · 2019-01-01 01:05

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

查看更多
骚的不知所云
3楼-- · 2019-01-01 01:13

As its creator I'm biased ;) but you could also consider using something like https://uppy.io. It does file uploading without navigating away from the page and offers a few bonuses like drag & drop, resuming uploads in case of browser crashes/flaky networks, and importing from e.g. Instagram. It's also open source and does not rely on jQuery or anything like that.

查看更多
梦该遗忘
4楼-- · 2019-01-01 01:14

If you are in fact seeking a pure javascript way to upload an image, then the following tutorial from 2009 will tell you exactly how to do that:

http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html

I ran into this when I wanted to add basic-authentication to a form submission, without enabling cookies. E.g. when you have username/password fields with your filename, file, etc fields.

Hope this helps!

查看更多
大哥的爱人
5楼-- · 2019-01-01 01:23

PURE JS

Use following code:

let formData = new FormData();
let req = new XMLHttpRequest();
let photo = document.getElementById("image-file").files[0];  // file from input

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);
  • In serwer side you can read original file name (and other info) which is automatically included to above request.
  • You NOT need to use xhr.setRequestHeader('Content-Type', 'multipart/form-data'); - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • This solution should works on all major browsers.

Editable example here. More info about response/error handling here.

查看更多
登录 后发表回答