2011-01-30 38 views
6

我在java中有一个字节数组形式的图像。我试图将该图像上传到我的Ruby on Rails应用程序,该应用程序使用Paperclip gem。我的Rails的模式是这样的:HTTP-POST将图像映射到Ruby on 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()); 
} 

这里的铁轨控制台上的新的调试:直接

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 

我在哪里出错?

+0

你在使用什么HTTP库? – 2011-01-30 22:33:14

+0

Apache Commons HTTPClient 4.1 – Raunak 2011-01-30 23:02:17

回答

2

我认为问题在于,如果没有名为app的参数,只有图像,您尝试使用params [:app]创建应用程序。我想在你创建的行动应改为工作如下:

@app = App.new(:image => params[:image]) 

另一个好东西可以添加以下验证在你的应用程序模型,以确保记录不会被保存到数据库中,如果没有图像保存。

validates_attachment_presence :image