Uploading a raw file to Rails using Carrierwave

前端 未结 1 1749
夕颜
夕颜 2020-12-24 09:37

My clients are trying to upload an image from Blackberry and Android phones. They don\'t like posting a)form parameters or b) multipart messages. What they would like to d

相关标签:
1条回答
  • 2020-12-24 09:54

    This can be done but you will still need your clients to send the orignal filename (and the content-type if you do any validation on the type).

    def photo
      tempfile = Tempfile.new("photoupload")
      tempfile.binmode
      tempfile << request.body.read
      tempfile.rewind
    
      photo_params = params.slice(:filename, :type, :head).merge(:tempfile => tempfile)
      photo = ActionDispatch::Http::UploadedFile.new(photo_params)
    
      @postcard = Postcard.find(params[:id])
      @postcard.photo = photo
    
      respond_to do |format|
        if @postcard.save
          format.json { head :ok }
        else
          format.json { render :json => @postcard.errors, :status => :unprocessable_entity }
        end
      end
    end
    

    And now you can set the photo using

    curl http://server/postcards/1/photo.json?filename=foo.png --data-binary @foo.png
    

    And to specify the content-type use &type=image/png.

    0 讨论(0)
提交回复
热议问题