Skip to main content
 首页 » 编程设计

python之上传 django rest framework api 时文件(pdf 除外)损坏

2024年08月14日42jillzhang

嘿,我遇到了一点问题。我写了一个 django restframework api 用于将文件上传到我的本地目录。就 pdf 而言,它似乎工作得很好,但任何其他类型的格式都会损坏文件并使其无法打开。

(这包括 png/jpg/任何其他图片格式、txt 文件、xlsx 文件等) 这些文件保存在正确的路径中非常好,它们被适本地命名没有问题。

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) 

更新: 我发现被篡改的文件中保存了额外的内容

------WebKitFormBoundaryKDALl9LeBZb6xbOo Content-Disposition:表单数据;名称="file";文件名="123.txt" 内容类型:文本/纯文本

文件数据

------WebKitFormBoundaryKDALl9LeBZb6xbOo--

请您参考如下方法:

FileUploadParser 假定传入请求是原始字节流并将其作为一个整体进行解析。通常是 listed on its own在 parser_classes 中,因为它将为任何类型的传入数据激活。

在您的情况下,您正在发送一个由 FileUploadParser 拾取的多部分请求,并且整个事情 - 边界和所有 - 保存为一个文件。因此,您会在文件中看到 WebKitFormBoundary。

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

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