我在将图像从Node js app上传到远程服务器时遇到问题。 远程服务器应用程序是Rails 5并使用paperclip来保存文件。 当我通过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
配置/初始化/ paperclip_spoof.rb
require 'paperclip/media_type_spoof_detector'
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
我需要你的帮助。谢谢你提前
答案 0 :(得分:0)
我只需要在将文件发送到服务器之前解码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);