如何使用 XHR 发送附件(图像)和嵌套参数以在钛中上传文件?

2023-12-28

我正在尝试将手机照片库中的图像上传到服务器。

图片库打开得很好。这是我的代码。

    var win = Ti.UI.createWindow({
        navBarHidden : true,
    });

    var ind = Titanium.UI.createProgressBar({
        width : 200,
        height : 50,
        min : 0,
        max : 1,
        value : 0,
        style : Titanium.UI.iPhone.ProgressBarStyle.PLAIN,
        top : 10,
        message : 'Uploading Image',
        font : {
            fontSize : 12,
            fontWeight : 'bold'
        },
        color : '#888'
    });

    win.add(ind);
    ind.show();

    var main_url = "http://10.0.0.4:3000";

    Titanium.Media.openPhotoGallery({

        success : function(event) {
            Ti.API.info("success! event: " + JSON.stringify(event));
            var imageview = event.media;

            var xhr = Titanium.Network.createHTTPClient();

            xhr.onerror = function(e) {
                Ti.API.info('IN ERROR ' + e.error);
            };
            xhr.onload = function() {
                Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
            };
            xhr.onsendstream = function(e) {
                ind.value = e.progress;
                Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress + ' ' + this.status + ' ' + this.readyState);
            };
            // open the client
            xhr.open('POST', main_url + '/images.json');
            xhr.setRequestHeader("Connection", "close");
            // send the data
            var params = "image[attachment]=" + imassage;
            xhr.send({
                media : imageview,
                title : "helloo helllo",
                desciption : "Sample Desciption",
                username : 'lorem',
                password : 'ipsum',
            });

        },
        cancel : function() {

        },
        error : function(error) {
        },
        allowImageEditing : true
    });

但我想发送嵌套参数,例如:

image[media] = image
image[title] = "helloo helllo",
image[desciption] = "helloo helllo",
user[name] = "lorem",
user[password] = "ipsum",

我尝试做类似的事情

  1. Try ONE

    var params = "图片[标题] = '你好你好'; 参数 = 参数 +"&image[media] = '+ imageview;

and then

等等...

xhr.open('POST', main_url + '/images.json',true);
xhr.setRequestHeader("Connection", "close");
// send the data
xhr.send({
    media : imageview,
    title : "helloo helllo",
    desciption : "Sample Desciption",
    username : 'lorem',
    password : 'ipsum',
});

但它会将图像作为 blob 而不是附件发送

  1. Try Two

    var params = "图片[标题] = '你好你好'; 参数 = 参数 +"&image[media] = '+ imageview;

and then

等等...

xhr.open('POST', main_url + '/images.json');
xhr.setRequestHeader("Connection", "close");
// send the data
xhr.send({
    media : imageview,
    title : "helloo helllo",
    desciption : "Sample Desciption",
    username : 'lorem',
    password : 'ipsum',
});

但它会将图像作为 blob 而不是附件发送

- - - - - 编辑 - - - - -

我成功地通过以下方式制作了嵌套参数:

    xhr.send({
        user_id : "1",
        image : {
            attachment : immage,                
            'title' : "helloo helllo",
            desciption : "Sample Desciption",
            download_type : 'free',
            price : '0.0',
            tag_list : 'jddhd'
        },
    });

但这返回为:

"image"=>"{
    \"title\":\"helloo helllo\",
    \"username\":\"lorem\",
    \"desciption\":\"Sample Desciption\",
    \"order\":\"name\",
    \"media\":\"[object TiBlob]\",
    \"password\":\"ipsum\"
}

但我需要接收参数,例如:

"image"=>{
    "title"=>"hello testing my uploads lorem",
    "description"=>"ssasd assdas asdas sad sadsa dsa ",
    "download_type"=>"free",
    "price"=>"0.0",
    "tag_list"=>"jddhd,akhdsa,"

    "attachment"=>#<ActionDispatch::Http::UploadedFile:0xb4c713e8 @original_filename="im.jpg",
    @content_type="image/jpeg",
    @headers="Content-Disposition: form-data; name=\"image[attachment]\"; filename=\"im.jpg\"\r\nContent-Type: image/jpeg\r\n",
    @tempfile=#<File:/tmp/RackMultipart20120429-6839-1w8vlxn>>,
}

如果我从附件:图片 from image{}然后它以所需的方式返回对象,即

    "attachment"=>#<ActionDispatch::Http::UploadedFile:0xb4c713e8 @original_filename="im.jpg",
    @content_type="image/jpeg",
    @headers="Content-Disposition: form-data; name=\"image[attachment]\"; filename=\"im.jpg\"\r\nContent-Type: image/jpeg\r\n",
    @tempfile=#<File:/tmp/RackMultipart20120429-6839-1w8vlxn>>

现在真的很困惑如何解决这个问题。谢谢


不确定您是否能够解决这个问题,但我在这个问题上挣扎了一段时间,并且能够通过使用以下格式动态生成哈希来使嵌套参数文件上传工作:

var params = {};
params['user[user_id]'] = 1;
params['user[image][attachment]'] = image;
params['user[image][title]'] = "helloo helllo";
params['user[image][description]'] = "Sample Description";
params['user[image][download_type]'] = "free";
params['user[image][price]'] = "0.0";
params['user[image][tag_list]'] = "jddhd";
xhr.send(params);

如果我尝试使用上面提供的格式创建哈希,则图像对象始终作为 TiBlob 字符串传输。上面的代码对我有用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 XHR 发送附件(图像)和嵌套参数以在钛中上传文件? 的相关文章

  • 从 Mailgun 表单 Post PHP 中检索附件

    如何检索并保存通过 Mailgun 的 POST 表单发送给我的附件 下面是一些参数 attachment 1 filename gt crabby gif type gt image gif name gt attachment 1 te
  • 在表单中编辑序列化哈希?

    我正在序列化存储在settings表中的字段 并且希望能够在表单字段中编辑该哈希 class Template lt ActiveRecord Base serialize settings end 但我就是这么做那么文本区域只显示序列化数
  • Ruby on Rails Webpacker 找不到 asset_pack_path 下的图像

    我在使用 Ruby on Rails Webpacker 在视图中包含图像时遇到问题 当我尝试使用 html img 标签和 asset pack path 在我的视图中插入图像时 出现错误 我的图像位于app javascript ima
  • 使用 C 通过引用传递数组

    是的 我已经阅读了这个问题和答案 在 C 中通过引用传递数组 https stackoverflow com questions 1106957 pass array by reference in c 我有一个类似的问题 并从该问题中实现
  • 使用 Mechanize (Ruby) 进行基本身份验证和表单身份验证

    我正在尝试登录公司内部网上的一个站点 该站点具有基本身份验证弹出对话框和基于表单的身份验证 这是我正在使用的代码 导致 401 gt Net HTTPUnauthorized 错误 require rubygems require mech
  • $.load 内的表单未正确发布

    这就是我得到的 基本上单击一个按钮并执行以下代码 Readthis MonsterRequest php id Mon TestVar TestVar replace s g Readthis Readthis htmlencode Tes
  • 从 Rails 3.1.3 升级到 Rails 3.2.1。资产错误

    我尝试将应用程序从 Rails 3 1 3 升级到 Rails 3 2 1 但资产出现问题 我有这样的错误 ActionController RoutingError No route matches GET assets logos op
  • RailsAdmin 中具有 join_table 和 has_many :through 的模型的路由错误

    所以我有3个模型 category product category products 这是我的category rb attr accessible name has many category products do def with
  • 启动同一作业的多个延迟作业进程

    我在运行多个工作人员的设置中使用延迟作业 就我的问题而言 这并不重要 但假设我运行 10 个工作线程 当前在开发模式下执行此操作 我遇到的问题是两个不同的工作人员有时开始处理同一项工作 调用我的工作对象上的执行方法 据我所知 延迟作业正在使
  • Capistrano:deploy.rb 文件重构

    我的deploy rb中有以下代码 namespace app do desc copies the configuration frile from shared config yml to config task copy config
  • Rails 3 best_in_place 编辑在不刷新页面的情况下无法工作

    我从Bernat的博客rails迷你教程中获取了评论代码 我尝试使用他的 best in place gem 添加就地编辑功能 在大多数情况下它工作正常 我的代码部署在http falling spring 3964 herokuapp c
  • 如果使用 jQuery 添加字段,Rails 嵌套表单属性不会保存

    我有一个带有嵌套表单的 Rails 表单 我使用 Ryan Bates 嵌套表单和 jquery 教程 并且就动态添加新字段而言 它工作得很好 但是当我提交表单时 它不会保存任何关联的属性 但是 如果在表单加载时构建部分 则它会很好地创建属
  • 保护 REST 和 JSON

    我想利用 RESTful 架构构建提供 JSON 数据的 Web 服务 但我只想要我自己的客户端应用程序可以从我的网络服务请求 基本上 我的 Web 服务包含不供公众使用的敏感数据 但我想以这种方式构建它 以便我可以构建连接到我的 Web
  • Rails 4.1 环境变量未重新加载

    我创建了一个application yml文件在配置目录中并添加了一些键值对 即AWS REGION us east 1 我还添加了以下内容application rb读取文件并更新 ENV 哈希 if Rails env developm
  • 在 Yosemite 上安装 Ruby 1.9.2 时出错

    我在 Yosemite 上使用 rvm 安装 ruby 1 9 2 时遇到错误 有人可以帮助我吗 我更新了自制程序和rvm 我正在与其他人合作处理这个项目 所以我无法升级 ruby 我在下面放置了我的输出的链接 提前致谢 Kanyons M
  • Rails3/will_paginate/Ajax - 下一个/上一个链接无法正常工作(这是一个错误吗?)

    我正在遵循 使用ajax分页 http railscasts com episodes 174 pagination with ajax railscast 用于我的 Rails 3 应用程序 一切似乎都运行良好 除了上一个和下一个链接根本
  • 如何将 devise/omniauth 重定向到我登录的页面?

    我通过omniauth 进行了身份验证 并且该链接通过layout application html haml 在每个页面上都可用 然而 当他们完成omniauth身份验证后 他们都会进入root权限 我如何设置它 以便他们重定向到他们单击
  • <%=h ... %> 在 Rails 中意味着什么?

    I found here http api rubyonrails org classes ActionView Helpers RecordTagHelper html以下语法 什么是h means 它用于转义标签的输出以避免跨站点脚本
  • GET 和 POST 方法有什么区别? [复制]

    这个问题在这里已经有答案了 可能的重复 什么时候用POST 什么时候用GET https stackoverflow com questions 46585 when do you use post and when do you use
  • 如何检查字符串是否为有效日期

    我有一个字符串 31 02 2010 并想检查它是否是有效日期 最好的方法是什么 我需要一个方法 如果字符串是有效日期 则返回 true 如果不是 则返回 false require date begin Date parse 31 02

随机推荐