Django文件上传 -- 适用于单一小文件上传

首先,在html模版中添加类似下面的代码

<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>

这里需要注意一下几点:

  1. form表单汇总一定要有enctype="multipart/form-data"属性
  2. form需要以POST方式提交
  3. form的Action属性对应views中处理upload上传逻辑的函数
  4. 需要有csrf_token这个标签,否则post无法提交
  5. 第一个<input>的类型为file,这是一个文件选择器,name属性很重要,因为后面通过此字段取出文件对象

 

接下来,编写CGI逻辑

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

posted @ 2013-01-28 11:01  bourneli  阅读(6784)  评论(0编辑  收藏  举报