一千萬個為什麽

搜索

不能在django上使用“image.save”

我的錯誤是:

IOError at /mytest/photo/upload/

[Errno 2] No such file or directory: u'/mytest/photo/upload/2.png'

我的觀點是:

UPLOAD_URL = '/mytest/photo/upload/'

def upload(request):
    buf = request.FILES.get('photo', None)
    print buf
    if buf:
        #data = buf.read()
        #f = StringIO.StringIO(data)
        image = Image.open(buf)
        #image = image.convert('RGB')
        name = '%s%s' % (UPLOAD_URL, buf.name)
        image.save(file(name, 'wb'), 'PNG')
        return HttpResponse('ok')
    return HttpResponse('no')

而我的urls.py是:

urlpatterns = patterns('mytest.views',
    url(r'^photo/upload/$','upload',name="")
)

我怎樣才能解決這個問題?

最佳答案

您必須指定要保存文件的本地路徑。 UPLOAD_URL是視圖的路徑,而不是目錄。

命名變量UPLOAD_PATH,其中包含完整的上傳路徑

然後做類似的事情:

UPLOAD_PATH = '/path/to/uploads/user'
if not os.path.isdir(UPLOAD_PATH):
    os.mkdir(UPLOAD_PATH)
file_path = os.path.join(UPLOAD_PATH, filename)
# security check
if os.path.abspath(file_path ).startswith(UPLOAD_PATH):
    image.save(file(file_path , 'wb'), 'PNG')

轉載註明原文: 不能在django上使用“image.save”