javascript jQuery 多文件从头上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28718621/
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
jQuery multiple file upload from scratch
提问by wiredmark
I am trying to implement a multiple image uploader in jQuery using the new HTML5 multipleattribute.
我正在尝试使用新的 HTML5多属性在 jQuery 中实现多图像上传器。
My code is the following:
我的代码如下:
<form action="file-upload.php" method="post" enctype="multipart/form-data">
<input name="userfiles" type="file" multiple="multiple">
</form>
The JS code I am using is taken from a discussion here on SO, and is the following:
我使用的 JS 代码取自关于 SO 的讨论,如下所示:
$('input[name=userfiles]').change(function() {
var names = [];
for (var i = 0; i < $(this).get(0).files.length; ++i) {
names.push($(this).get(0).files[i].name);
console.log(names[i]);
}
});
With this I am able to print on the console the file names I select, but what if I need to get the exact val() of those files? I tried replacing .namewith .val(), but I get an error.
有了这个,我可以在控制台上打印我选择的文件名,但是如果我需要获取这些文件的确切 val() 怎么办?我试图取代。名称与.VAL() ,但我得到一个错误。
I think I would need a fakepathof every single file if I want to be able to work with them with $.ajax. If this is correct, how can I cycle though them in the PHP file where the get request is sent, in order to upload them?
我想我会需要一个fakepath每一个文件,如果我希望能够与他们合作以$阿贾克斯。如果这是正确的,我如何在发送 get 请求的 PHP 文件中循环浏览它们,以便上传它们?
回答by insanebits
You can make use of HTML5 FormData API. https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
您可以使用 HTML5 FormData API。https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
var form = new FormData();
for (var i = 0; i < $(this).get(0).files.length; ++i) {
form.append('userfiles[]', $(this).get(0).files[i]);
}
// send form data with ajax
$.ajax({
url: 'url',
type: "POST",
data: form
});
Or if you cannot use FormData there is a way to send it natively: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
或者,如果您不能使用 FormData,则有一种方法可以本地发送它:https: //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
回答by ?rel
You don't need to manipulate file path, in your ajax call just use the File and put it into a new FormData
您不需要操作文件路径,在 ajax 调用中只需使用 File 并将其放入新的 FormData
Something like that:
类似的东西:
$.ajax({
'type':'POST',
'data': (new FormData()).append('file', $(this).get(0).files[i])
See HTML5 multiple file upload: upload one by one through AJAX
回答by Jordan Micle
If you use jquery-file-upload plugin you can use this
如果您使用 jquery-file-upload 插件,您可以使用它
<input class="fileupload" type="file" name="file">
and
和
$('.fileupload').each(function () {
$(this).fileupload({
//your code goes here
})