【问题标题】:Paperclip not saving image because of wrong content type由于内容类型错误,回形针未保存图像
【发布时间】:2018-04-28 05:11:52
【问题描述】:

我在将图像从 Node js 应用程序上传到远程服务器时遇到问题。 远程服务器应用程序是 Rails 5,并使用回形针保存文件。 当我通过 Postman 上传图片时,图片保存成功,一切正常。但问题是当我从前端节点应用程序上传时,图像没有保存,这是我在日志中看到的

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

在网上查了一下,好像我在前端节点应用程序中没有正确编码文件。这是我的代码

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)
})

谁能指导我如何解决这个问题?

我什至尝试在我的后端应用程序中覆盖内容类型验证,但仍然无法正常工作。

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

我需要你的帮助。提前谢谢你

【问题讨论】:

    标签: ruby-on-rails node.js paperclip form-data node-fetch


    【解决方案1】:

    我只需要在将文件发送到服务器之前对 base64 进行解码

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多