有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java HTTPPOST向Ruby on Rails应用程序发布一个图像

我有一个java字节数组形式的图像。我正试图将这张图片上传到我的Ruby on Rails应用程序中,该应用程序使用了回形针宝石。我的Rails模型如下所示:

class App < ActiveRecord::Base
  has_attached_file :image
end

当我执行java代码时,我在rails应用程序中得到HHTTP/1.1 302 Found响应。 更新了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

直接从浏览器上传图像就像一种魅力。下面是控制器/apps\u控制器的实现。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

我哪里做错了


共 (1) 个答案

  1. # 1 楼答案

    我认为问题在于,当没有名为App的参数,只有image时,您尝试使用params[:App]创建应用程序。我认为以下创建操作应该起作用:

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

    另一个好方法是在应用程序模型中添加以下验证,以确保在未保存图像的情况下不会将记录保存到数据库中

    validates_attachment_presence :image