Python 图像上传
我想用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文件的代码
import os import uuid from pyramid.response import Responsedef store_mp3_view(request):
# filename
变量里存的是文件名,格式是字符串。
# 注意:这个例子没有处理IE浏览器发送的绝对文件路径作为文件名的情况。这个例子比较简单,信任用户输入。
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
这段代码可以让你一次上传多个文件。
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')
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()
我用上面的代码让它工作了,希望对你有帮助。