无法使用Appcelerator将图像上载到远程服务器

时间:2012-09-03 20:36:48

标签: request titanium appcelerator image-uploading

我正在使用的应用程序使用由另一个团队开发的API。我正在使用Titanium 2.1.2,我正在尝试使用所述API上传照片。我正在使用Appcelerator的HTTPClient来发出请求。这是我的代码:

    var url = 'http://api.veramiko.com/albums/' + album.veramiko_id + '/photos';
    var photo = imageView.toBlob();

    var args = { //parameters sent to post photo
        file : photo,
        description : descriptionText
    };

    var client = Ti.Network.createHTTPClient({
        onload : function(e){
            Ti.API.info(this.responseText); //Print the result
        },
        onerror : function(e){
            Ti.API.error(this.responseText); //Print the result
        },
        timeout : 60000
    });
    client.open('POST', url);
    client.setRequestHeader('Authorization', 'Bearer ' + token);
    client.setRequestHeader('Content-type', "multipart/form-data");
    client.send(args);

令牌是我们用来授权对服务器发出的任何请求的变量。我认为只将图像从ImageView转换为Blob就足以发送照片,但照片不会上传。帖子是根据描述创建的,但照片未正确发送。

我是否需要添加其他内容?将照片作为Blob发送是正确的吗?

编辑:我读了这个link并尝试了以下内容但没有结果:

    var url = 'http://api.veramiko.com/albums/' + album.veramiko_id + '/photos';
    var boundary = '-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var photo = imageView.toBlob();

    var args = {
        file : photo,
        description : descriptionText.value
    };      

    var contentDisposition = "--" + boundary + "\r\n"; 
    contentDisposition += "Content-Disposition: form-data; name=\"file\";";
    contentDisposition += "filename=\"" + imageView.image + "\"\r\n\";";
    contentDisposition += "Content-Type: application/octet-stream\r\n\r\n";

    var fullContent = contentDisposition + photo  + "\r\n--" + boundary + "--";

    alert(JSON.stringify(args));
    var token = JSON.parse(Ti.App.Properties.getString('loggedUser', 'No existe')).networks[0].token;
    var client = Ti.Network.createHTTPClient({
        onload : function(e){
            Ti.API.info(this.responseText); //Print the result
        },
        onerror : function(e){
            Ti.API.error(this.responseText); //Print the result
        },
        timeout : 60000
    });
    client.open('POST', url);
    client.setRequestHeader('Authorization', 'Bearer ' + token);
    client.setRequestHeader('Content-Type', "multipart/form-data; boundary=\"" + boundary + "\"");
    client.setRequestHeader('Connection', 'close');
    client.send(fullContent);

我尝试使用Content-Disposition和Content-Type标头包装文件但没有结果。

4 个答案:

答案 0 :(得分:1)

我终于找到了解决这个问题的方法。请参阅以下link

这就是我的代码最终的样子:

    // I put the contents of my image into a variable
var f = imageHolder.toImage();
    // I create a random name for the image
var tmpName = (new Date()).getTime().toString() + '.png';
    // I create a folder where I will store the photo temporally
var g = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'picturesToUpload');
if (!g.exists()) {
    // If the directory doesn't exist, make it
    g.createDirectory();
};
var photo = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'picturesToUpload', tmpName);
    // write the contents of the image into the file
photo.write(f);
    // I create my url with the albumId where I'll upload the picture
var url = 'http://api.veramiko.com/albums/' + albumId + '/photos';
var args = {
    file : photo.read(), // I read the contents of the file
    description : ''
}
var token = JSON.parse(Ti.App.Properties.getString('loggedUser', 'No existe')).networks[0].token;
var client = Ti.Network.createHTTPClient({
    onload : function(e){
        Ti.API.info('Info received from the uploading: ' + this.responseText);
    },
    onerror : function(e){
        Ti.API.debug('Error: ' + this.responseText);
    },
        timeout : 60000
});
client.open('POST', url);
    // these headers are important
client.setRequestHeader('enctype', 'multipart/form-data');
client.setRequestHeader('Content-Type', 'image/png');
client.setRequestHeader('Authorization', 'Bearer ' + token);
client.send(args);

希望此信息可以帮助更多人。

答案 1 :(得分:0)

首先,清除API参数是什么。以及你想要使用TOKEN的地方。

var imageView = Ti.UI.createImageView({
    backgroundImage : "image.png",
});
    var url = 'http://api.veramiko.com/albums/' + album.veramiko_id + '/photos';


        var args = { //parameters sent to post photo
            file : imageView.backgroundImage,
            description : descriptionText,
            token : "Token",
        };

        var client = Ti.Network.createHTTPClient({
            onload : function(e){
                Ti.API.info(this.responseText); //Print the result
            },
            onerror : function(e){
                Ti.API.error(this.responseText); //Print the result
            },
            timeout : 60000
        });
        client.open('POST', url);
        client.setRequestHeader("Content-type","multipart/form-data");
        client.setRequestHeader("Content-length", args.length);
        client.send(args);

试试这个,我觉得这对你有用......

答案 2 :(得分:0)

我找到了本教程,其中介绍了如何构建上传器。

Titanium Mobile: Build an Image Uploader

答案 3 :(得分:0)

您需要使用此代码以表单数据形式上传文件:

var baseurlAPI = "YOUR API BASEURL HERE";
var file = Ti.Filesystem.getFile(pathToFile);

 if(file.exists()){
    var xhr = Ti.Network.createHTTPClient({
        onload: function(e) {
                Ti.API.log('success '+this.responseText);
       },
       onerror: function(e) {
                Ti.API.error(this.responseText);
        },
            timeout : -1
    });
    xhr.open('POST', baseurlAPI);
    xhr.send({
       file: file
    });
 }else{
    console.log('didnt exist ' + file.nativePath);
 }