简体   繁体   中英

Paperclip not saving image because of wrong content type

I am having issues uploading an image from Node js app to a remote server. The remote server app is Rails 5 and using paperclip to save the file. When I upload the image through Postman , the image is saved successfully and everything works fine. But the issue is when I upload from front end Node app, The image is not saved and this is what I see in the logs

begin transaction Command :: file -b --mime '/var/folders/90/d3rv8dkd3t1g9wwz90dtk_dx41mg3d/T/b5e7d988cfdb78bc3be1a9c221a8f74420171114-33517-11gthzp.png'
[paperclip] Content Type Spoof: Filename image1.png (text/plain from 
Headers, ["image/png"] from Extension), content type discovered from 
file command: text/plain. See documentation to allow this combination.
rollback transaction

After researching online, it seems like I am not encoding the file correctly in the front end node app.Here is my code

var FormData = require('form-data');
var fetch = require('node-fetch');

var form = new FormData();
form.append('name', req.body.name);
form.append('image', req.body.attachment, req.body.filename);

fetch('http://localhost:3000/slides', { method: 'POST', body: form,headers: form.getHeaders()})
.then(function(res) {
    return res.json();
}).then(function(json) {
    console.log(json);
});
  res.json(resp)
})

Can someone guide me how to fix this?

I have even tried to override content type validation in my backend app, but still doesn't work.

class Slide < ApplicationRecord
  has_attached_file :image, styles: { small: "64x64", med: "100x100", large: "200x200" }
  validates_attachment_content_type :image, :content_type => ["image/jpg", "text/plain","image/jpeg", "image/png", "image/gif"]

 end

config/initializer/paperclip_spoof.rb

require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

Please I need your help.Thank you in advance

I just had to decode the base64 before sending the file to the server

var buff = new 
Buffer(req.body.attachment.replace(/^data:image\/\w+;base64,/, ""), 'base64');  
fs.writeFileSync('image.png', buff);
var form = new FormData();
form.append('name', "some name");
form.append('image', buff, req.body.filename);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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