上载Django RestFramework API时文件(PDF除外)损坏 [英] Files (except pdfs) Corrupted when uploading django restframework api

查看:78
本文介绍了上载Django RestFramework API时文件(PDF除外)损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有点问题。我写了一个Django restframework api,用于将文件上传到本地目录。看来,对于pdf来说,它工作得非常好,但是任何其他类型的格式都会损坏文件,使其无法打开。

Hey so i'm having a bit of an issue. I wrote a django restframework api for uploading files to my local directory. It seems like it works perfectly fine when it comes to pdfs, but any other type of format damages the file and make it unable to open.

(其中包括png / jpg /其他任何图片格式,txt文件,xlsx文件等)
这些文件可以正确地保存在正确的路径中,它们的命名正确无问题。

(this includes png/jpg/any other picture format, txt files, xlsx files, and etc) The files are saved perfectly fine in the correct path, they're named appropriately without issue.

class UploadInvoiceFile(APIView):
     parser_classes = (FileUploadParser, MultiPartParser)

     def put(self, request, filename, specific_path='admin'):
         file_obj = request.data['file']
         file_path = settings.INVOICE_URL[admin]
         file = file_path+'/'+filename

         if not os.path.exists(file_path):
             os.makedirs(file_path)
         with open(file, 'wb+') as destination:
             for chunk in file_obj.chunks():
                 destination.write(chunk)



         return Response(status=204)

更新:
我发现,被裁剪的文件中还保存了其他内容

UPDATE: I found out that the files that are curropted have additional stuff saved to them

------ WebKitFormBoundaryKDALl9LeBZb6xbOo
内容处置:表单数据; name =文件; filename = 123.txt
内容类型:文本/纯文本

------WebKitFormBoundaryKDALl9LeBZb6xbOo Content-Disposition: form-data; name="file"; filename="123.txt" Content-Type: text/plain

文件数据

------ WebKitFormBoundaryKDALl9LeBZb6xbOo-

------WebKitFormBoundaryKDALl9LeBZb6xbOo--

推荐答案

FileUploadParser 假定传入的请求是原始字节流,并将其整体解析。通常在<$ c $中单独列出 c> parser_classes ,因为它将针对任何类型的传入数据激活。

The FileUploadParser assumes that an incoming request is a raw byte stream and parses it as a whole. It's typically listed on its own in parser_classes since it will activate for any type of incoming data.

您的情况是,您要发送多部分 FileUploadParser 接收到的请求,整个内容-边界和全部-保存为文件。因此,您会在文件中看到 WebKitFormBoundary

What's happening in your case, is that you're sending a multipart request which is being picked up by FileUploadParser and the whole thing - boundaries and all - saved as a file. Hence you see the WebKitFormBoundary in the files.

您应该删除 FileUploadParser parser_classes 中的c $ c>并让 MultiPartParser 正确解析多部分请求。

You should drop FileUploadParser from parser_classes and let the MultiPartParser correctly parse the multipart request.

class UploadInvoiceFile(APIView):
     parser_classes = (MultiPartParser, )

这篇关于上载Django RestFramework API时文件(PDF除外)损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆