开发者

Titanium Appcelerator Multi File upload

开发者 https://www.devze.com 2023-04-11 02:40 出处:网络
I\'m Developing with Appcelerator SDK 1.6.2 for iOS 4.3 I\'m trying to upload multiple files to a server, the problem is the number of files is dynamic and therefore cant be predetermined in the pa

I'm Developing with Appcelerator SDK 1.6.2 for iOS 4.3

I'm trying to upload multiple files to a server, the problem is the number of files is dynamic and therefore cant be predetermined in the params of the XHR send.

If I pass one file in it works fine but I cant seem to figure out how to pass in many.

I've tried creating an array to hold the media elements but no dice.

var media = [];
for(var i = 0; i < sync.images.length; i++){
     media[i] = Titanium.Filesystem.getFile(sync.images[i].path).read();
}

xhr.send({
    media: media // no workie
//  media: media[1] workie
});

I found this article: http://developer.appcelerator.com/question开发者_运维技巧/123794/multiple-file-upload-in-one-request

that assumes the following code should work:

 xhr.send({      
     'media[]': imageFile.read(),
     'media[]': imageFile2.read()
 });

however i'm uncertain how to obtain this dynamically due to the fact that the number of images transferred can vary

Suggestions would be great


I had this exact problem, and I ended up using the Object.defineProperty method. Here's how your code could be modified:

Change media into an object instead of an array, then iteratively define properties:

var media = {};

for(var i = 0; i < sync.images.length; i++){
    data_blob = Titanium.Filesystem.getFile(sync.images[i].path).read();
    data_key = 'image'+i;
    Object.defineProperty(media, data_key, {value: data_blob, enumerable: true});
}

xhr.send(media);

Here's the mozilla doc for defineProperty:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2FdefineProperty#Adding_properties_and_default_values


You want use the xhr in POST parameter, so xhr.open("POST", url);

Second off, try each file in a different object index, for example:

{
   file1: imageFile.read(),
   file2: imageFile2.read()
}

To grab in PHP, just do $_FILE['file1'], $_FILE['file2'] ... etc.


I also ran into this problem and the current marked answer didn't work for me. After some debugging i've found a better solution.

First set the parameters(Note: leave {} if you don't need extra keys / values).

var parameters = {'extraKey': 'extraValue'};

After that loop through your files and add them to the parameters.

for(var i in files) parameters['files[' + i +']'] = files[i];

Your parameters will look like this after the loop:

{'extraKey':'extraValue', 'file[0]': files[0], 'file[1]': files[1] }

Now you can send them like xhr.send(parameters);

It's 5 years late but hey I also got here ^^.

0

精彩评论

暂无评论...
验证码 换一张
取 消