jQuery上传进度和AJAX文件上传

时间:2022-12-09 19:48:40

It seems like I have not clearly communicated my problem. I need to send a file (using AJAX) and I need to get the upload progress of the file using the Nginx HttpUploadProgressModule. I need a good solution to this problem. I have tried with the jquery.uploadprogress plugin, but I am finding myself having to rewrite much of it to get it to work in all browsers and to send the file using AJAX.

看来我还没有把我的问题说清楚。我需要发送一个文件(使用AJAX),我需要使用Nginx HttpUploadProgressModule来获取文件的上传进度。我需要一个好的解决这个问题的方法。我试过jquery。uploadprogress插件,但我发现自己不得不重写大部分内容以使它在所有浏览器中工作,并使用AJAX发送文件。

All I need is the code to do this and it needs to work in all major browsers (Chrome, Safari, FireFox, and IE). It would be even better If I could get a solution that will handle multiple file uploads.

我所需要的是代码来完成这个工作,并且需要在所有主要的浏览器中工作(Chrome、Safari、FireFox和IE)。如果我能找到一个能够处理多个文件上传的解决方案,那就更好了。

I am using the jquery.uploadprogress plugin to get the upload progress of a file from the NginxHttpUploadProgressModule. This is inside an iframe for a facebook application. It works in firefox, but it fails in chrome/safari.

我正在使用jquery。uploadprogress插件从NginxHttpUploadProgressModule获取文件的上传进度。这是facebook应用程序的iframe。它在firefox中工作,但在chrome/safari中失败。

When I open the console I get this.

当我打开控制台时,我得到了这个。

Uncaught ReferenceError: progressFrame is not defined
jquery.uploadprogress.js:80

Any idea how I would fix that?

你知道我该怎么解决吗?

I would like to also send the file using AJAX when it is completed. How would I implement that?

我还想在文件完成时使用AJAX发送它。我怎么实现它呢?

EDIT:
I need this soon and it is important so I am going to put a 100 point bounty on this question. The first person to answer it will receive the 100 points.

编辑:我很快就需要这个,它很重要,所以我要对这个问题加100分奖励。第一个回答的人将得到100分。

EDIT 2:
Jake33 helped me solve the first problem. First person to leave a response with how to send the file with ajax too will receive the 100 points.

编辑2:Jake33帮助我解决了第一个问题。第一个留下如何用ajax发送文件的回复的人也会收到100分。

2 个解决方案

#1


197  

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

现在用AJAX上传文件是可行的。是的,是AJAX,而不是像swf或java这样蹩脚的AJAX。

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

这个例子可以帮助您解决:https://webblocks.nl/tests/ajax/file-drag-drop.html。

(It also includes the drag/drop interface but that's easily ignored.)

(它还包括拖放界面,但很容易被忽略。)

Basically what it comes down to is this:

基本上可以归结为:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

(演示:http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

基本上就是这个=)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

文件类型为Blob: http://www.w3.org/TR/FileAPI/ ?

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

另一个更好的方法是使用FormData。这允许您1)命名一个文件,如表单,2)发送其他东西(文件),如表单。

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

FormData使服务器代码更简洁,更向后兼容(因为现在请求的格式与普通表单完全相同)。

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

所有这些都不是实验性的,而是非常现代的。Chrome 8+和火狐4+知道该怎么做,但我不知道其他的。

This is how I handled the request (1 image per request) in PHP:

这就是我如何处理PHP中的请求(每个请求一个图像):

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

#2


15  

Here are some options for using AJAX to upload files:

以下是使用AJAX上传文件的一些选项:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

更新:这是一个用于多个文件上传的JQuery插件。

#1


197  

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

现在用AJAX上传文件是可行的。是的,是AJAX,而不是像swf或java这样蹩脚的AJAX。

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

这个例子可以帮助您解决:https://webblocks.nl/tests/ajax/file-drag-drop.html。

(It also includes the drag/drop interface but that's easily ignored.)

(它还包括拖放界面,但很容易被忽略。)

Basically what it comes down to is this:

基本上可以归结为:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

(演示:http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

基本上就是这个=)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

文件类型为Blob: http://www.w3.org/TR/FileAPI/ ?

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

另一个更好的方法是使用FormData。这允许您1)命名一个文件,如表单,2)发送其他东西(文件),如表单。

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

FormData使服务器代码更简洁,更向后兼容(因为现在请求的格式与普通表单完全相同)。

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

所有这些都不是实验性的,而是非常现代的。Chrome 8+和火狐4+知道该怎么做,但我不知道其他的。

This is how I handled the request (1 image per request) in PHP:

这就是我如何处理PHP中的请求(每个请求一个图像):

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

#2


15  

Here are some options for using AJAX to upload files:

以下是使用AJAX上传文件的一些选项:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

更新:这是一个用于多个文件上传的JQuery插件。