我正在使用rails和grape编写REST API,我需要上传文件。
post :create_file do
path = Rails.root.join 'public','uploads',params[:name]
File.open(path,'wb'){|f| f.write(request.body.read) }
{
message:'success'
}
end
上传文本文件时效果很好; 但是在上传二进制文件时会出现问题,例如文件损坏。
标头:HTTP/1.1
*/*
no-cache
localhost:3000
Keep-Alive
Apache-HttpClient/4.3.2 (java 1.5)
gzip,deflate
nil
PARAMS:
name:"test.png"
'test.png':Hashie::Mash (5 elements)
'rout_info':'version=, method=POST, path=/api/users/create_file(.:format)
我将代码更改为:
post :create_file do
path = Rails.root.join 'public','uploads',params[:name]
file = params['bg.png']
file2 = request.body
File.open(path,'wb'){|f| f.write(file2.read) }
{
message:file.read
}
end
调试消息: 文件:
filename="bg.png"
type="application/octet-stream"
name="bg.png"
tempfile=#<File:0x007fd7694b9bd0>
head="Content-Disposition: form-data; name="bg.png"; filename="bg.png"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary"
file2的:
#<File:0x007fd7694c8270>
如果我使用file.read
,我会得到一个空文件,如果我使用file2.read
,我的文件就会被破坏。
==========================================
最后它被file.tempfile.read
解决了
非常感谢@maxd
答案 0 :(得分:-1)
您的客户应指定正确的Content-Type
标头并以相应的格式上传二进制数据:
如果您想将二进制数据上传为请求正文,请指定application/octet-stream
(好像您要编码接受此格式的数据):
Content-Type: application/octet-stream
或指定multipart/form-data
并在multipart format上传二进制数据(详情为here):
Content-type: multipart/form-data