javascript 如何使用javascript上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29910490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:16:57  来源:igfitidea点击:

How to upload file using javascript?

javascript

提问by Sam

<form method="post" action="#" onsubmit="uploadImage">
    <input type="file" name="imgFile" >
    <input type="submit" id="submit" value="upload">
</form>

How can I upload an image using javascript with ajax call.

如何使用带有ajax调用的javascript上传图像。

回答by skylying

Yes, it is possible, here's very simple code example :

是的,这是可能的,这是一个非常简单的代码示例:

function upload()
{
    var data = new FormData(),
        files = // some <input type="file" />

    data.append('image', files[0]);

    $.ajax({
        url: // Your ajax url, say it's upload.php,
        type: 'post',
        dataType: 'json',
        data: data,
        processData: false,
        contentType: false,
        success: function(image)
        {
            // whatever you want to do 
        }
    });
};

Then in upload.php you need to pick $_POSTvalue and do the upload with move_uploaded_filesort of things.

然后在upload.php 中,您需要选择$_POST值并执行上传move_uploaded_file操作。

回答by Wh1T3h4Ck5

This is just a quick JavaScript solution if you want pure JS.

如果您想要纯 JS,这只是一个快速的 JavaScript 解决方案。

var file = document.getElementById('id of your input:file').files[0];
var ajax = new XMLHttpRequest;

var formData = new FormData;
formData.append('imagefile', file);

ajax.upload.addEventListener("progress", myProgressHandler, false);
ajax.addEventListener('load', myOnLoadHandler, false);
ajax.open('POST', 'upload.php', true);
ajax.send(formData);

Note:Some sources say that calling Ajax's openmethod should come after creating an object (before any work with ajaxin this case) but me personally never had any troubles using it this way. So it's up to you.

注意:一些消息来源说调用 Ajax 的open方法应该在创建对象之后(ajax在这种情况下在任何工作之前)进行,但我个人从来没有以这种方式使用它。所以这取决于你。

Events:

事件:

function myProgressHandler(event) {
  //your code to track upload progress
  var p = Math.floor(event.loaded/event.total*100);
  document.title = p+'%';
}

function myOnLoadHandler(event) {
  // your code on finished upload
  alert (event.target.responseText);
}

You can also add more event handlers such as "error" or "abort". Course, you need to write upload.phpto handle uploaded files (PHP is just an example; there are a lot of examples how to do that on SO).

您还可以添加更多事件处理程序,例如“ error”或“ abort”。当然,您需要编写upload.php来处理上传的文件(PHP 只是一个示例;在 SO 上有很多示例如何做到这一点)。

All you need is to make Ajax call on "change" event of your input-file element (upper part of code).

您所需要的只是对change输入文件元素(代码的上部)的“ ”事件进行 Ajax 调用。

In addition, you can write some featuresCheckfunction so if user's browser doesn't support something, provide basic file upload instead.

此外,您可以编写一些featuresCheck函数,如果用户的浏览器不支持某些功能,请提供基本的文件上传。

function featuresCheck() {
  var res = window.XMLHttpRequest && window.FormData && window.addEventListener;
  if (res) return true; else return false;
}

/* and test it in your code */
if (featuresCheck()) {
  // use ajax upload
  }
else {
  // use simple file uploader
  }

If you want to use multipleproperty of file-input you can't use .files[0](first file selected) and you'll need some loop through files list and do separate uploads for each of them (async of course).

如果你想使用multiple文件输入的属性,你不能使用.files[0](选择第一个文件),你需要一些循环文件列表并为每个文件单独上传(当然是异步的)。

Be aware of security. Do double check of uploaded files before you move them from temp location (check MIME type, extension, rename them).

注意安全。在将上传的文件从临时位置移动之前,请仔细检查它们(检查 MIME 类型、扩展名、重命名它们)。