在没有multipart / form-data的情况下重新上传Flask中的文件 [英] ReSTfully upload file in Flask without multipart/form-data
问题描述
我试图将一个二进制文件上传到Flask端点,而不使用任何类型的 multipart / form-data
。我想简单地将 POST
或 PUT
文件中的数据传送到端点,并将其保存到文件在服务器上。我能找到的唯一例子,以及其他问题中讨论的唯一方法是使用 multipart / form-data
。
下面的作品,但SHA256哈希通常不匹配,而上传作为 form-data
工作正常。
@ application.route(/ rupload /< filename>,methods = ['POST','PUT'])
def rupload(filename):
#完整性检查和设置跳过。
文件名= secure_filename(文件名)
fileFullPath = os.path.join(UPLOAD_FOLDER,文件名)
$ b $打开(fileFullPath,'wb')为f:
f.write(request.get_data())
return jsonify({
'filename':filename,
'size':os.path.getsize fileFullPath)
})
另外,上面的内存效率很低。有没有办法通过某种类型的缓冲流将其写入输出文件?感谢!
$ b
编辑:这是我测试这个:
curl -v -H'Content-Type:application / octet-stream'-X POST --data @ test.zip https://example.com/test/rupload/test.zip
编辑: - data-binary
没有区别。
你试过用hashlib吗? b $ b
import hashlib
...
@ application.route(/ rupload /< filename>,methods = ['POST', 'PUT'])
def rupload(文件名):
#完整性检查和设置跳过。
文件名= secure_filename(文件名)
fileFullPath = os.path.join(UPLOAD_FOLDER,文件名)
file_hash = hashlib.sha256()
打开(fileFullPath, 'wb +')为f:
input = request.get_data()
f.write(输入)
file_hash.update(输入)
...
fileDigest = file_hash.hexdigest()
I'm trying to upload a binary file to a Flask endpoint without using any type of multipart/form-data
. I'd like to simply POST
or PUT
the data inside the file to the endpoint, and save it to a file on the server. The only examples I can find, and the only method discussed in other questions, uses multipart/form-data
.
The following "works", but the SHA256 hashes usually don't match, whereas uploading as form-data
works fine.
@application.route("/rupload/<filename>", methods=['POST', 'PUT'])
def rupload(filename):
# Sanity checks and setup skipped.
filename = secure_filename(filename)
fileFullPath = os.path.join(UPLOAD_FOLDER, filename)
with open(fileFullPath, 'wb') as f:
f.write(request.get_data())
return jsonify({
'filename': filename,
'size': os.path.getsize(fileFullPath)
})
Additionally, the above is very inefficient with memory. Is there a way to write it to the output file via some type of buffered stream? Thanks!
Edit: This is how I'm testing this:
curl -v -H 'Content-Type: application/octet-stream' -X POST --data @test.zip https://example.com/test/rupload/test.zip
Edit: --data-binary
makes no difference.
Have you tried using hashlib?
import hashlib
...
@application.route("/rupload/<filename>", methods=['POST', 'PUT'])
def rupload(filename):
# Sanity checks and setup skipped.
filename = secure_filename(filename)
fileFullPath = os.path.join(UPLOAD_FOLDER, filename)
file_hash = hashlib.sha256()
with open(fileFullPath, 'wb+') as f:
input = request.get_data()
f.write(input)
file_hash.update(input)
...
fileDigest = file_hash.hexdigest()
这篇关于在没有multipart / form-data的情况下重新上传Flask中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!