图像上传Python

时间:2014-04-21 10:40:57

标签: python html

我想浏览图片&使用python将图像上传到我的应用程序中的文件夹

当我点击提交按钮时,它会显示http://www.domain.com/store_mp3_view&图片未上传

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form action="/store_mp3_view" method="post" accept-charset="utf-8"
      enctype="multipart/form-data">

    <label for="mp3">Mp3</label>
    <input id="mp3" name="mp3" type="file" value="" />

    <input type="submit" value="submit" />
</form>
</body>
</html>

python文件代码 进口口 导入uuid 来自pyramid.response import Response

def store_mp3_view(请求):      #filename包含字符串格式的文件名。     #     #警告:此示例不处理IE发送的事实     #absolute file path 作为文件名。这个例子很幼稚;它     #信任用户输入。

filename = request.POST['mp3'].filename

# ``input_file`` contains the actual file data which needs to be
# stored somewhere.

input_file = request.POST['mp3'].file

# Note that we are generating our own filename instead of trusting
# the incoming filename since that might result in insecure paths.
# Please note that in a real application you would not use /tmp,
# and if you write to an untrusted location you will need to do
# some extra work to prevent symlink attacks.

file_path = os.path.join(/files, '%s.mp3' % uuid.uuid4())

# We first write to a temporary file to prevent incomplete files from
# being used.

temp_file_path = file_path + '~'
output_file = open(temp_file_path, 'wb')

# Finally write the data to a temporary file
input_file.seek(0)
while True:
    data = input_file.read(2<<16)
    if not data:
        break
    output_file.write(data)

# If your data is really critical you may want to force it to disk first
# using output_file.flush(); os.fsync(output_file.fileno())

output_file.close()

# Now that we know the file has been fully saved to disk move it into place.

os.rename(temp_file_path, file_path)

return Response('OK')
return Response('OK')

2 个答案:

答案 0 :(得分:0)

您可以在models.py

中使用模型文件字段
class Document(models.Model):
    docfile = models.FileField(upload_to='documents/', max_length=5234,blank=True, null=True,)

相应的forms.py

class DocumentForm(forms.Form):
    docfile = forms.FileField(label='', show_hidden_initial='none',required=True,)

在views.py

if request.FILES.has_key('your_fileName'):
            newdoc = Document(docfile = request.FILES['your_fileName'])
            newdoc.save()

我使用上面的代码,希望它有帮助

答案 1 :(得分:0)

使用此代码,您可以上传多个文件

def insert_file(self):
    for i in request.FILES.getlist('mp3'):
        fileName = i.name
        out_file = open(fileName,'w')
        out_file.write(i.read())
    return HttpResponse('Inserted Successfully')