如何正确下载带有django请求的文件
我正在运行一个Django应用程序,在那里我可以上传文件。现在我想使用请求下载文件。我试图创建一个下载文件的视图,这样我就可以通过请求进行调用。但这不太管用如何正确下载带有django请求的文件,django,django-rest-framework,django-views,django-file-upload,Django,Django Rest Framework,Django Views,Django File Upload,我正在运行一个Django应用程序,在那里我可以上传文件。现在我想使用请求下载文件。我试图创建一个下载文件的视图,这样我就可以通过请求进行调用。但这不太管用 My model: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(storage=PrivateMediaSt
My model:
class FileCollection(models.Model):
name = models.CharField(max_length=120, null=True, blank=True)
store_file = models.FileField(storage=PrivateMediaStorage(), null=True, blank=True)
creation_date = models.DateTimeField(null=True, blank=True)
它告诉我TypeError:应该是str、bytes或os.PathLike对象,而不是FieldFile
如果我传入apiview/admin中提供的url,我会得到:FileNotFoundError:[Errno 2]没有这样的文件或目录
还尝试:
def fileview(request):
path = FileCollection.objects.first()
obj = path.store_file
o = str(obj)
file_path = os.path.join(settings.MEDIA_ROOT, o)
print(file_path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(),
content_type="application/vnd.ms-excel")
response[
'Content-Disposition'] = 'inline; filename=' + os.path.basename(
file_path)
return response
但这给了我ValueError:视图文件_storage_api.api.v1.views.fileview没有返回HttpResponse对象。它没有返回任何结果
这样做对吗
我非常感谢你的帮助或提示。
非常感谢
file_path = file.store_file
不是文件路径,而是文件字段的实例
试用
file_path = file.store_file.name
然后使用第二个代码段
编辑:以下是我使用的代码:
l_targetFile是实际文件的路径
l_prjPath = os.path.realpath(os.path.dirname(__file__)).replace(<adapt the path here>)
l_userFileName= <file field>.name.replace('<upload to sub-dir>','')
l_targetFile = l_prjPath + '/media/' + l_fileObj.file_obj.name
#return the file
response = FileResponse(open(l_targetFile, 'rb'),\
(l_responseDisposition == 'attachment'))
#process the filename as stored on the local machine in case of download
try:
#check if it will throw
l_tmpUserName = l_userFileName.encode('ascii')
#no error use the non-encoded filename
l_fileExpr = 'filename="{0}"'.format(l_userFileName)
except UnicodeEncodeError:
# Handle a non-ASCII filename
l_fileExpr = "filename*=utf-8''{}".format(quote(l_userFileName))
response['Content-Disposition'] = '{0};{1};'.format(l_responseDisposition,l_fileExpr)
if '.pdf' in l_userFileName:
response['Content-Type'] = 'application/pdf'
elif l_dataSource == CMSArchiveEntry.SOURCE_TAG:
response['Content-Type'] = 'text/html; charset=utf-8'
return response
谢谢我的朋友!当我尝试这一点,我仍然得到文件未找到错误,即使该文件存在。它在AWS bucket中,但django仍然应该找到它,对吗?我通过以下方式进行管理:file\u path=file.store\u file read\u file=file\u path.readAWS不应该更改任何内容,但配置显然存在一些问题。name应返回一个相对于媒体根目录的路径。我将在下面添加用于呈现文件响应的代码
l_prjPath = os.path.realpath(os.path.dirname(__file__)).replace(<adapt the path here>)
l_userFileName= <file field>.name.replace('<upload to sub-dir>','')
l_targetFile = l_prjPath + '/media/' + l_fileObj.file_obj.name
#return the file
response = FileResponse(open(l_targetFile, 'rb'),\
(l_responseDisposition == 'attachment'))
#process the filename as stored on the local machine in case of download
try:
#check if it will throw
l_tmpUserName = l_userFileName.encode('ascii')
#no error use the non-encoded filename
l_fileExpr = 'filename="{0}"'.format(l_userFileName)
except UnicodeEncodeError:
# Handle a non-ASCII filename
l_fileExpr = "filename*=utf-8''{}".format(quote(l_userFileName))
response['Content-Disposition'] = '{0};{1};'.format(l_responseDisposition,l_fileExpr)
if '.pdf' in l_userFileName:
response['Content-Type'] = 'application/pdf'
elif l_dataSource == CMSArchiveEntry.SOURCE_TAG:
response['Content-Type'] = 'text/html; charset=utf-8'
return response