首先,在html模版中添加类似下面的代码
|
1
2
3
4
5
|
<
form
enctype="multipart/form-data" method="POST" action="/view/process/upload/file">
{% csrf_token %}
<
input
type="file" name="your_file"/>
<
input
type="submit" value="上传文件" />
</
form
>
|
这里需要注意一下几点:
- form表单汇总一定要有enctype="multipart/form-data"属性
- form需要以POST方式提交
- form的Action属性对应views中处理upload上传逻辑的函数
- 需要有csrf_token这个标签,否则post无法提交
- 第一个<input>的类型为file,这是一个文件选择器,name属性很重要,因为后面通过此字段取出文件对象
接下来,编写CGI逻辑
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
def
process_upload_file(request):
# 获取文件
file_obj
=
request.FILES.get(
'your_file'
,
None
)
if
file_obj
=
=
None
:
return
HttpResponse(
'file not existing in the request'
)
# 写入文件
file_name
=
'temp_file-%d'
%
random.randint(
0
,
100000
)
# 不能使用文件名称,因为存在中文,会引起内部错误
file_full_path
=
os.path.join(UPLOAD_ROOT, file_name)
dest
=
open
(file_full_path,
'wb+'
)
dest.write(file_obj.read())
dest.close()
return
render_to_response(
'upload_result.html'
,{})
|
取用文件的方式为:“file_obj = request.FILES.get('file', None)”。第一个参数”your_file”对应form中的第一个input标签。然后,可以通过file_obj.name获取文件名称,file_obj.read()方法获取文件内容。上传的文件放在内存中,所以此方法只适合小文件上传。
参考资料:
http://blog.donews.com/limodou/archive/2006/03/23/783974.aspx
声明:如有转载本博文章,请注明出处。您的支持是我的动力!文章部分内容来自互联网,本人不负任何法律责任
本文转自bourneli博客园博客,原文链接:
http://www.cnblogs.com/bourneli/archive/2013/01/28/2879574.html
,如需转载请自行联系原作者