How to upload images via Ajax?

stackov8

I make a form for upload image:

gem paperclip install

Form:

<%= 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 %>

Controller:

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  

Loading images works OK.

The console displays:

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)

I'd like to upload images via 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);
    }        
  })
}); 

but this method does not work: the image is not loaded and console displays:

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)
Зелёный

As you can see from the log file, your ajax doesn't pass an image file:.

First:

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

Second:

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

Try to debug next line:

$.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);
    }        
  })

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to upload multiple images to one post in facebook via api

From Dev

How to upload multiple images to one post in facebook via api

From Dev

Upload images via FileAPI and PHP

From Dev

How to upload file via an AJAX form in Zend Framework 2?

From Dev

Wicket: upload data via ajax

From Dev

Submit file upload via Ajax

From Dev

image upload via ajax php

From Dev

Upload images to Facebook wall via python and Graphapi

From Dev

Which is the better approach to upload images via nginx?

From Dev

codeigniter form upload with images using ajax

From Dev

Can you upload images using Ajax?

From Dev

How to upload several images with httpPost?

From Dev

Django Rest Framework: Upload file via AJAX

From Dev

Laravel5 file Upload via Ajax

From Dev

Image upload via Ajax in PHP[simplest way]

From Dev

Bind click to images loaded via AJAX

From Dev

Fancybox - Add more images to gallery via ajax

From Dev

How to upload multiple image with Ajax?

From Dev

HTML5 File API Upload Multiple Images with Ajax

From Java

How to Pick files and Images for upload with flutter web

From Dev

How can i upload images with NodeJS and express?

From Dev

How to upload images like png into GitHub repository?

From Dev

How to upload all gallery images to a server in Android ?

From Dev

How to upload images to GitHub without gimmicks (on a Mac)?

From Dev

How to upload images with cloud kit using swift?

From Dev

how to upload multiple images to a blog post in django

From Dev

How to upload images taken by raspberry to AWS IoT

From Dev

How to upload 2 separate images in codeigniter

From Dev

How do I to show images before upload?

Related Related

HotTag

Archive