实现简单的django上传文件

  本文用django实现上传文件并保存到指定路径下,没有使用forms和models,步骤如下:

1、在模板中使用form表单,因为这个表单使用于上传文件的,所以method属性必须设置为post,而且enctype必须设置为"multipart/form-data",这个表明不对字符进行编码,代码如下:

<form enctype="multipart/form-data" action="/upLoadFile/" method="post">  
   <input type="filename" name="ufile" />  
   <br/>  
   <input type="submit" value="上传"/>  
</form>

2、设置urls.py文件,在点击上传按钮时,指定实现上传功能的视图函数,代码如下:

url(r'^upLoadFile/$', upload_file, name='upload_file'),

3、实现视图函数,虽然文件是通过post方式上传的,但文件并不存在request.POST中,而是存放在request.FILES中,所以使用request.FILES["ufile"]或request.FILES.get("ufile", "")来获取上传文件,代码如下:

def upload_file(request):
    if not request.method == "POST":
        return HttpResponse("请使用POST提交!")
    else:
        my_file = request.FILES.get("upload_file", None)    # 获取上传的文件,如果没有文件,则默认为None
        if not my_file:
            return HttpResponse("No files for upload!")
        else:
            destination = open(os.path.join("/data/upload", my_file.name), 'wb+')    # 打开特定的文件进行二进制的写操作
            for chunk in my_file.chunks():      # 分块写入文件
                destination.write(chunk)
            destination.close()
            return HttpResponse("上传成功!")

4、测试,点击选择上传文件,点击上传,页面显示"上传成功",在/data/upload目录下面找到上传的文件,至此,最简单的用django上传文件就完成了。

 

posted on 2016-09-29 10:58  你又跑调了  阅读(249)  评论(0编辑  收藏  举报