如何使用Javascript将多个文件上载到服务器

时间:2012-01-26 02:31:34

标签: javascript cordova

我正在使用PhoneGap,并上传一个文件(使用HTTP POST),像这样,

function uploadSingleFile()
{
    var ft = new FileTransfer();
    // set up parameters etc
    ft.upload(imageName, "http://serviceaddress/UploadFile.ashx", win, fail, options);
}

function win(r)
{
    // success callback
}

我想上传多个文件,所以在成功回调中我想调用uploadSingleFile移动到下一个文件。

如何存储我最喜欢的文件?我使用localStorage存储文件名。所以我想这样做,

upload file localStorage.file0
upload file localStorage.file1
upload file localStorage.file2

所以我需要做的就是将数字存储在我们所处的最后,0,1等等。我需要使用全局变量吗?看起来很乱。

如果我只能通过成功回调一个数字作为附加参数?

3 个答案:

答案 0 :(得分:0)

嗯。这个问题值得怀疑吗?只需存储一组文件名,并使用JSON.stringify / JSON.parse进行数组和字符串之间的转换。

答案 1 :(得分:0)

function uploadSingleFile(fileName) {

  var ft = new FileTransfer();

  ft.upload("fileUrl",
            "server",
            function (result , fileName) {
              console.log(fileName + ' has been uploaded successfully to server');                                          
            },
            function (error) {
              console.log(error);
            },
            {fileName: fileName, fileKey: "file"});
}

function uploadFiles() {
  var files = JSON.parse(localStorage.files);

  for(var i=0; i < files.length; i++) {
    uploadSingleFile(files[i]);
  }
}

您可以将file of index作为参数发送到uploadSingleFile(),然后在console.log()

中使用它

答案 2 :(得分:-1)

首先将所有图片添加到数组中:

var TemplstImg = [];

function UploadImages()
{

    var lstImages = [localStorage.file0,localStorage.file1,localStorage.file2];
    TemplstImg=lstImages  ;

    if (TemplstImg.length > 0) {
        var img = TemplstImg.pop();
        uploadPhoto(img);
    }
}

function uploadPhoto(imageURI) {

    imageURI = imageURI.ImageFile;

    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
    options.mimeType = "image/jpeg";

    var params = {};
    params.value1 = "test";
    params.value2 = "param";

    options.params = params;

    var ft = new FileTransfer();

    ft.upload(imageURI, yourServerPath, winImg, failImg,options);
}

function winImg(r) {

    if (TemplstImg.length == 0) {
        alert ('Done , all files was uploaded'); 

    } else {
        var img = TemplstImg.pop();
        uploadPhoto(img);
    }
}

function failImg(error) {

    alert("failImg An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}