首页 > Web开发 > 详细

Django文件上传实例

时间:2017-08-18 19:17:48      阅读:297      评论:0      收藏:0      [点我收藏+]

近日在用Django框架开发过程中遇到上传用户头像问题,经多方搜索资料,终于解决问题!

1.首先,在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>

这里需要注意一下几点:

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

 

2.接下来,编写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()方法获取文件内容。上传的文件放在内存中,所以此方法只适合小文件上传。

Django文件上传实例

原文:http://www.cnblogs.com/leonardchen/p/7391238.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!