简体   繁体   English

Flask应用程序文件上传-获取文件内容时出错

[英]Flask Application File Upload - Error while getting contents of file

I am developing a flask application which uploads a file to IBM Bluemix Cloudant DB. 我正在开发一个flask应用程序,该应用程序将文件上传到IBM Bluemix Cloudant DB。 I need to save the contents of the file as a key value pair in Cloudant. 我需要在Cloudant中将文件内容另存为键值对。 If I try to save a text file, it reads the content correctly. 如果我尝试保存一个文本文件,它将正确读取内容。 For other type of files it does not work. 对于其他类型的文件,它不起作用。 Following is my flask REST API CODE: 以下是我的烧瓶REST API代码:

@app.route('/upload', methods=['POST'])
def upload_file():
    file_to_upload = request.files['file_upload'];
    response = CloudantDB().upload_file_to_db(file_to_upload);

//tHE FUNCTION upload_file under CloudantDB is as shown below.
file_name = file.filename;
uploaded_file_content = file.read();
data = {
            'file_name': file_name,
            'file_contents': uploaded_file_content,
            'version': version
            }
my_doc = self.database.create_document(data);

I know the error is because "uploaded_file_content" is in a different format (ie For PDFs, JPGs etc). 我知道错误是因为“ uploaded_file_content”格式不同(例如,对于PDF,JPG等)。 Is there anyway I can overcome this? 反正有什么我可以克服的?

Thanks! 谢谢!

The difference is that text files contain ordinary text whereas JPG, PNG etc. contain binary data. 区别在于文本文件包含普通文本,而JPG,PNG等包含二进制数据。

Binary data should be uploaded as an attachment with a mime type, and you need to base64 encode the data. 二进制数据应作为带有mime类型的附件上传,并且您需要对数据进行base64编码。 You don't show what create_document() is doing, but it's unlikely that it is able to treat binary data as an attachment. 您没有显示create_document()在做什么,但是不太可能将二进制数据视为附件。 This might fix it for you: 这可能会为您解决:

from base64 import b64encode

uploaded_file_content = b64encode(file.read());
data = {
    'file_name': file_name,
    'version': version,

    '_attachments': {
        file_name : {
            'content-type': 'image/png',
            'data': uploaded_file_content
        }
    }
}

my_doc = self.database.create_document(data);

It should also be possible with your current code to simply base64 encode the file content and upload it. 您当前的代码也应该可以简单地对文件内容进行base64编码并上传。 So that you know what type of data is stored should you later retrieve it, you will need to add another key value pair to store the mime type as content-type does above. 为了知道以后要检索的数据类型,将需要添加另一个键值对来存储mime类型,就像上面的content-type一样。

Attachments have advantages in that they can be individually addressed, read, deleted, updated without affecting the containing document, so you are probably better off using them. 附件的优点是可以单独寻址,读取,删除,更新附件,而不会影响所包含的文档,因此使用它们可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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