【发布时间】:2011-01-30 20:41:14
【问题描述】:
我在 java 中有一个字节数组形式的图像。我正在尝试将该图像上传到我的 Ruby on Rails 应用程序,该应用程序使用了 Paperclip gem。我的 Rails 模型如下所示:
class App < ActiveRecord::Base
has_attached_file :image
end
当我执行 java 代码时,我得到 HHTTP/1.1 302 Found 响应我的 rails 应用程序。
更新了 java HTTP-Post 方法。
这是我用于 HTTP-Post 的新 Java 代码:
public void postFile(byte[] image) throws ClientProtocolException, IOException{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:3000/apps");
ContentBody cb = new ByteArrayBody(image, "image/jpg", "icon.jpg");
//ContentBody cb = new InputStreamBody(new ByteArrayInputStream(image), "image/jpg", "icon.jpg");
MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpentity.addPart("image", cb);
httppost.setEntity(mpentity);
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
}
这是 rails 控制台上的新调试:
Started POST "/apps" for 127.0.0.1 at Mon Jan 31 00:26:07 +0000 2011
Processing by AppsController#create as HTML
Parameters: {"image"=>#<ActionDispatch::Http::UploadedFile:0x1041491c8 @content_type=nil, @original_filename="icon.jpg", @headers="Content-Disposition: form-data; name=\"image\"; filename=\"icon.jpg\"\r\n", @tempfile=#<File:/var/folders/NU/NUcfnxwVHmmnVUo9JUdNok+++TI/-Tmp-/RackMultipart20110131-3735-1ylugl7-0>>}
SQL (0.1ms) BEGIN
SQL (1.0ms) describe `apps`
AREL (0.4ms) INSERT INTO `apps` (`appName`, `image_file_size`, `created_at`, `image_updated_at`, `image_file_name`, `image_content_type`, `updated_at`) VALUES (NULL, NULL, '2011-01-31 00:26:07', NULL, NULL, NULL, '2011-01-31 00:26:07')
[paperclip] Saving attachments.
SQL (1.3ms) COMMIT
Redirected to http://localhost:3000/apps/36
Completed 302 Found in 18ms
直接从浏览器上传图片就像一个魅力。下面是controller/apps_controller.rb的实现:
def create
@app = App.new(params[:app])
respond_to do |format|
if @app.save
format.html { redirect_to(@app, :notice => 'App was successfully created.') }
format.xml { render :xml => @app, :status => :created, :location => @app }
format.json { render :json => @app, :status => :created, :location => @app }
else
format.html { render :action => "new" }
format.xml { render :xml => @app.errors, :status => :unprocessable_entity }
format.json { render :json => @app.errors, :status => :unprocessable_entity }
end
end
end
我哪里错了?
【问题讨论】:
-
你使用的是什么 HTTP 库?
-
Apache Commons HTTPClient 4.1
-
从日志看来,一个条目被插入到数据库并且附件被保存,你能确认是不是这样吗?在 AppsController 中查看 create 操作也会很有趣,您能否将其也包含在您的问题中?
-
@DanneManne。是的,一个条目被插入到数据库中,但附件没有被保存。如果您查看调试,您还会注意到所有值都设置为 null。我还在 ApplicationController 中注释掉了protect_from_forgery;在注释掉protect_from_forgery之前,我得到了无效的authentity_token。
标签: java ruby-on-rails-3 paperclip http-post