Skip to content


Django 1.0之后的文件上传

今天实现了另一个RockSun在线工具,按照指定编码和换行格式保存文件,能够将数据按照GBK或者UTF编码、以及Windows和Linux换行保存并直接让用户下载,也可以由用户上传的文件转化后直接下载。可能会有bug,有点累,先不多想了。

首先说一下直接提示用户下载文件的功能,没有多说的,就是往http的response头里增加两句话,用django的语法写就是:

        response = HttpResponse(text, mimetype='application/octet-stream')
        response['Content-Disposition'] = 'attachment; filename=%s' %filename.encode('utf8')
        return response

此外,网上说django上传文件的介绍似乎都是1.o之前的方法,最后还是直接看官方文档比较准确,文档在这里:http://docs.djangoproject.com/en/dev/topics/http/file-uploads/,这里简单说一下,首先是form,没有什么特别的:

<form enctype=”multipart/form-data” action=”/someurl” method=”post”>
<input type=”file” name=”file”/>

</form>

然后,在views中可以直接读文件内容和文件名:

        text = file_obj.read()
        filename = file_obj.name

在默认情况下,小于2.5M的文件会存放到内存里,如果文件比较大则会存放为临时文件,对大文件最好不要直接read,而是用chunks方式读取,详细还是要读文档。

Related posts:

  1. Flash Zoom
  2. My first wordpress plugin
  3. Resize Image In Context Menu
  4. Gimp Crop Script
  5. Watermark: With GIMP Script

Posted in program. Tagged with , , , , , .

2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. xxxxxxxxx said

    你什么都没说。
    官方文档专门坑人。
    整一个upload_to在model里又没什么用,在view里,还要自己处理文件路径和文件名的。
    def handle_uploaded_file(f):
    destination = open(’some/file/name.txt’, ‘wb+’)
    for chunk in f.chunks():
    destination.write(chunk)
    destination.close()

  2. 我说了,1.0作了一些改变

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.