---
title: "Django上传文件"
author: "huangro"
date: "2009-11-26T18:06:48Z"
tags: []
slug: "django"
draft: false
lastmod: "2009-11-26T18:06:48Z"
id: 528393
url: "https://huangro.iteye.com/blog/528393"
---

之前写了一个上传文件模块，但是当文件很大时就会挂掉，分析了一下，原来是我将文件所有数据先读到内存，然后再写入文件，这样极大占用了CPU资源。现改进了下：

```python

def upload_file(request):
    file_obj = request.FILES.get('file', None)
    if file_obj:
        str_time = time.strftime('%Y-%m-%d_%H:%M:%S',time.localtime(time.time()))
        fname = file_obj.name;
        fname = str_time + fname[fname.rfind('.'):]
        of = open(UPLOAD_DIR+fname, 'wb+')
        for chunk in file_obj.chunks():
            of.write(chunk)
        of.close()
        
    return HttpResponseRedirect('/')

```