python - Django中PILsave图片,[Errno 2] No such file or directory

查看:1082
本文介绍了python - Django中PILsave图片,[Errno 2] No such file or directory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

views.py的代码如下:

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from PIL import Image

def show(request):
    d_content={}
    if request.method == "POST":
        reqfiles=request.FILES
        if len(request.FILES) > 0:
            reqfile=request.FILES['picfile']
            img=Image.open(reqfile)
            img.thumbnail((500,500),Image.ANTIALIAS)
            img.save('imgupload/static/ori_img.jpg','jpeg')
            d_content['ori_img']='ori_img.jpg'
            d_content['print']='ok'

    return render(request,'imgupload/showimg.html',d_content)

图1:本机测试正常,没问题。上传服务器才出问题


图2:同样代码,服务器上传图片后,出错

提示IOError,No such file or directory

图3:Django出错页面下面的debug可以看到,是在img.save的使用,调用open()出错了


本机开发环境是:mac系统,python2.7,Django1.10
开发环境服务器是CentOS6.5,python2.7,Django1.10,httpd2.4

排查错误

  • 在本机运行是无错的,python代码应该没问题,如图1.

  • 服务器Django环境没问题,其他页面都ok,只有这里报错

  • 是不是Linux文件权限问题?把服务器的mysite文件夹都chmod -R 777 没有效果,还是出错

  • 在服务器控制台直接python,然后import PIL,Image.open()然后再save一个图片,也是没问题的。


请教如何解决该问题?

解决方案

纠结了好久
反复看过官方文档后,终于找到答案了

原来

  • 在本地测试的时候,runserver会搜索各个app中的static,所以本机测试是没问题的。

  • 但是部署时,是不生效的,必须自己指定static文件夹。

然后在httpd的conf中,设置别名

Alias /static/ /root/workplace/mysite/static/

就可以正常访问了

这篇关于python - Django中PILsave图片,[Errno 2] No such file or directory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆