问题描述
我正在使用 PDFKit 生成 PDF,并且我能够成功地将 PDF 保存到我的本地系统并打开和查看该文件。然后我尝试通过 POST 请求将该 PDF 上传到我的 Django REST API。
问题:当Django收到请求时,我能够接收文件并获取文件的名称和大小并将其保存到媒体目录。但是,当我打开发送到服务器的文件(我之前在我的系统上打开过)时,它给了我一个错误,说它无法打开文件。
我不确定是什么导致了这种情况,我曾尝试研究任何类型的编码,但意识到这不适用于二进制文件,所以我知道这不是答案。我尝试将文件包装在不同类型(如 ContentFile)中,但没有成功。我将在下面发布我的代码。任何帮助将不胜感激。
Models.py
class Report(models.Model):
asset = models.ForeignKey(Asset,on_delete=models.CASCADE)
pdf = models.FileField(upload_to='reports/%Y/%m/%d/',null=True,blank=True)
Views.py
class GenerateReportView(APIView):
parser_classes = [FileUploadParser]
def post(self,request):
report_id = request.query_params.get('report_id')
report_pdf = request.data['file']
# Get the report object
report = Report.objects.filter(id=report_id).first()
# Save the generated pdf to the report
print("Type: " + type(report_pdf))
print("Size: " + str(report_pdf.size))
print("Name: " + report_pdf.name)
report.pdf.save(report_pdf.name,ContentFile(report_pdf.read()))
# Update the report to show it has Now generated the requested report
report.request_complete = True
report.save()
return Response({'message': 'PDF Successfully Uploaded'},status=status.HTTP_200_OK)
视图打印行的输出:
might also want to increase the JMeter log level for the Throughput Shaping Timer
提前致谢!!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)