【发布时间】:2020-08-24 10:11:37
【问题描述】:
我正在尝试下载存储在媒体文件夹中的文件,它似乎只在我将完整路径写入时才有效:
file_location = '/home/user/user.pythonanywhere.com/media/'
在 pythonanywhere 的设置页面中,“媒体 url”指向同一个目录。所以我真的不明白为什么我不能写 /media/ 来代替完整的路径。
这与我的 settings.py 文件有关吗?我有这些行:
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
MEDIA_URL="/media/"
我需要这些行吗?
这是我的下载功能:
class RequestFile(APIView):
def get(self, request):
#Returns the last uploaded file
#Remember if deleting files, only database record is deleted. The file must be deleted
obj = FileUploads.objects.all().order_by('-id')
file_location = '/home/user/user.pythonanywhere.com/media/' + str(obj[0].lastpkg)
x = file_location.find("/")
filename = file_location[x+1:]
print(file_location)
print(filename)
try:
with open(file_location, 'rb') as f:
filex_data = f.read()
#print("filex_data= ", filex_data)
# sending response
response = HttpResponse(filex_data, content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename=' + filename
except IOError:
# handle file not exist case here
response = HttpResponseNotFound('File not exist')
return response
如果我转到指向此类的 url,我将获得下载。
【问题讨论】:
-
下载文件到底是什么意思,请举例说明您是如何使用媒体文件的
-
我现在添加了下载功能。谢谢/彼得
标签: django django-media