"create", "con-6ren">
gpt4 book ai didi

java - android/rails 分段上传问题

转载 作者:行者123 更新时间:2023-11-30 11:59:28 26 4
gpt4 key购买 nike

我的问题是我尝试将图像和一些文本值上传到 Rails 服务器,而文本值最终变成文件,而不仅仅是参数值。

帖子在服务器上的样子

Parameters: {"action"=>"create", "controller"=>"problems",
"problem"=>{"lon"=>#File:/tmp/RackMultipart20100404-598-8pi1vj-0>,
"photos_attributes"=>{"0"=>{"image"=>#File:/tmp/RackMultipart20100404-598-pak6jk-0>}},
"subject"=>#File:/tmp/RackMultipart20100404-598-nje11p-0>,
"category_id"=>#File:/tmp/RackMultipart20100404-598-ijy1oo-0>,
"lat"=>#File:/tmp/RackMultipart20100404-598-1a7140w-0>,
"email"=>#File:/tmp/RackMultipart20100404-598-1b7w6jp-0>}}

部分android代码

try {
File file = new File(Environment.getExternalStorageDirectory(),"FMS_photo.jpg");

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://homepage.com/path");
FileBody bin = new FileBody(file);


Charset chars = Charset.forName("UTF-8");

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("problem[photos_attributes][0][image]", bin);
reqEntity.addPart("problem[category_id]", new StringBody("17", chars));

post.setEntity(reqEntity);
HttpResponse response = client.execute(post);

HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}

return true;

} catch (Exception ex) {

globalStatus = UPLOAD_ERROR;
serverResponse = "";
return false;
} finally {

}

最佳答案

这就是 Rails 处理多部分表单数据的方式。

为了方便,我在我的 ApplicationController 中添加了这个 before_filter:

def read_and_parse_json_file_params
file_params = params.select { |name,value| value.is_a?(File) || value.is_a?(Tempfile) }
file_params.reject! { |name,file| file.content_type !~ %r{^application/json} }

file_params.each do |name,file|
file.rewind
params[name] = ActiveSupport::JSON.decode(file.read)
end
end

它将每个部分解析为 JSON 哈希。

关于java - android/rails 分段上传问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2573018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com