繁体   English   中英

如何通过Ajax上传图像?

[英]How to upload images via Ajax?

我制作一张上传图片的表格:

gem paperclip install

形成:

<%= form_for(@image) do |f| %>
    <%= f.text_area(:description, rows: 4, class: 'form-control') %>
    <%= f.file_field :image, class: "desc_album" %>
    <%= f.submit 'Загрузить картинку', class: 'btn btn-default pull-right', id: 'loadImage' %>      
<% end %>

控制器:

def create  
  p '-------------------1'
  @image = Image.create(image_params)   

  if @image.save
    p '-------------------2'
    @image.update_attributes(user: current_user)

    render json: @image, :status => 200 
  else
    p '-------------------3'
    render json: @image.errors.full_messages, :status => 403 
  end
end  

加载图像即可。

控制台显示:

Started POST "/images" for 127.0.0.1 at 2015-08-01 15:47:16 +0300
Processing by ImagesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"PINHYvwaOerh2tFwIP8ad8Td8SPQmxh6m2Oy/uE0FzrdCn5UFRIf68KJ4/4fzzPLXITkScyhahlE+fU8mDUwEg==", "image"=>{"description"=>"gggggggggggggggggggggggggggg", "image"=>#<ActionDispatch::Http::UploadedFile:0x007fd62c55f7d0 @tempfile=#<Tempfile:/tmp/RackMultipart20150801-2493-1cks177.jpg>, @original_filename="f3.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"image[image]\"; filename=\"f3.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Загрузить картинку"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 8]]
"-------------------1"
Command :: file -b --mime '/tmp/1779cf3aa50c413afc7e05adb7e1b0de20150801-2493-116a994.jpg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/1779cf3aa50c413afc7e05adb7e1b0de20150801-2493-1wgxiwt.
...........
.............
......
Command :: file -b --mime '/tmp/1779cf3aa50c413afc7e05adb7e1b0de20150801-2493-1stgg9u.jpg'
  SQL (0.5ms)  INSERT INTO "images" ("description", "image_file_name", "image_content_type", "image_file_size", "image_updated_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["description", "gggggggggggggggggggggggggggg"], ["image_file_name", "f3.jpg"], ["image_content_type", "image/jpeg"], ["image_file_size", "8602"], ["image_updated_at", "2015-08-01 15:47:16 +0300"], ["created_at", "2015-08-01 12:47:16.575017"], ["updated_at", "2015-08-01 12:47:16.575017"]]
   (22.5ms)  COMMIT
   (0.2ms)  BEGIN
   (0.1ms)  COMMIT
"-------------------2"
   (0.1ms)  BEGIN
  SQL (0.4ms)  UPDATE "images" SET "user_id" = $1, "updated_at" = $2 WHERE "images"."id" = $3  [["user_id", 8], ["updated_at", "2015-08-01 12:47:16.677588"], ["id", 2]]
   (17.3ms)  COMMIT
Completed 200 OK in 459ms (Views: 0.7ms | ActiveRecord: 41.7ms)

我想通过Ajax.js上传图像:

$('#new_image').on('submit', function(e){
  e.preventDefault();

  $.ajax({
    url: '/images',
    type: 'POST',
    dataType: "JSON", 
    data: $('#new_image').serialize(),
    success: function(image){
      alert('im load success');
    },
    error: function(xhr, ajaxOptions, thrownError){
      alert(xhr.responseText);
    }        
  })
}); 

但是此方法无效:未加载映像,控制台显示:

Started POST "/images" for 127.0.0.1 at 2015-08-01 16:00:01 +0300
Processing by ImagesController#create as JSON
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"uqqR6HtkkYDuhWoFHHCmll2mWuzEHfBtpMQ/A2hwivZbI6jekmy3gc3WWIsjQI8qxf9Phtgngg57XnjBEXGt3g==", "image"=>{"description"=>"ggggggggggggggggggggggggggggg"}}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 8]]
"-------------------1"
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
"-------------------3"
Completed 403 Forbidden in 8ms (Views: 0.2ms | ActiveRecord: 0.6ms)

从日志文件中可以看到, ajax不会传递图像文件:。

第一:

Parameters: {"utf8"=>"✓", ... "image"=>{"description"=>"gg..."}}

第二:

Parameters: {"utf8"=>"✓", ... "image"=>{"description"=>"gg...", "image"=>#<ActionDispatch::Http::UploadedFile:0x007fd62c55f7d0 @tempfile=#<Tempfile:/tmp/RackMultipart20150801-2493-1cks177.jpg>, @original_filename="f3.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name

尝试调试下一行:

$.ajax({
    url: '/images',
    type: 'POST',
    dataType: "JSON", 
    data: $('#new_image').serialize(),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    success: function(image){
      alert('im load success');
    },
    error: function(xhr, ajaxOptions, thrownError){
      alert(xhr.responseText);
    }        
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM