我有2种上传图片的方法,一种是通过文件(image
),另一种是通过网址(imageURL
)。如果用户选择了url,我有一个模型方法从url下载文件:
class Post(models.Model):
...
image = models.FileField(null=True, blank=True)
imageURL = models.URLField(null=True, blank=True)
def download_file_from_url(self):
print('DOWNLOAD') #prints
# Stream the image from the url
try:
request = requests.get(self, stream=True)
except requests.exceptions.RequestException as e:
# TODO: log error here
return None
if request.status_code != requests.codes.ok:
# TODO: log error here
return None
# Create a temporary file
lf = tempfile.NamedTemporaryFile()
# Read the streamed image in sections
for block in request.iter_content(1024 * 8):
# If no more file then stop
if not block:
break
# Write image block to temporary file
lf.write(block)
print('WRITE') #prints
return files.File(lf)
视图
def post(request):
...
if form_post.is_valid():
instance = form_post.save(commit=False)
if instance.imageURL:
instance.image = Post.download_file_from_url(instance.imageURL)
instance.save()
从文件上传图像工作正常..但是当通过url上传时,模型方法会返回此错误:
SuspiciousFileOperation at /post/
The joined path (/var/folders/t9/7v8mki3s3h39fzylxfpsk9640000nn/T/tmpmvb9wxq6) is located outside of the base path component (/Users/zorgan/Desktop/app/draft1/media)
有人可以解释这意味着什么吗?它显然没有上传到media
文件夹,但我不知道/var/folders/
是什么。我的所有媒体文件都上传到标准media
文件夹:
网址
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
设置
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
,通过文件(image
)上传时效果很好。它只会在通过网址imageURL
上传时返回错误。知道问题是什么吗?