2013-04-24 58 views
1

我使用自定義函數上傳文件,如文件here所示,將文件分成塊。 我的問題是handle_uploaded_file()上傳我的文件兩次後,調用save(),一個上傳到「MEDIA_URL/my_path」目錄,一個上傳到「MEDIA_URL」。 但我想只有一個上傳,一個大塊。 可以強制save()上傳'chunked'嗎? 或者我應該使用不同的方法? 謝謝。使用塊上傳文件:避免保存兩次

  • models.py

    class ShapeFile(models.Model): 
        name = models.CharField(max_length=100) 
        srid = models.ForeignKey(SpatialRefSys) 
        user = models.ForeignKey(User) 
        color_table = models.ForeignKey(ColorTable) 
        file = models.FileField(upload_to="my_path") 
        class Meta: 
         unique_together = ('name', 'user') 
    
  • forms.py

    class UploadForm(ModelForm): 
        class Meta: 
         model = ShapeFile 
         fields = ('name','user','srid','file','color_table') 
         widgets = {'srid': TextInput(), 
            'user': HiddenInput() 
    
  • views.py

    def handle_uploaded_file(fileName, filePath): 
        with open(filePath, 'wb+') as destination: 
         for chunk in fileName.chunks(): 
          destination.write(chunk) 
    
    @login_required 
    def shapeIng(request): 
        if request.method == 'POST': 
         form = UploadForm(request.POST, request.FILES) 
         if form.is_valid(): 
          req = request.POST 
    
          # Split uploaded file into chunks 
          fileName = request.FILES['file'] 
          filePath = ShapeFile(file=fileName).file.path 
          handle_uploaded_file(fileName, filePath) 
    
          form.save() 
    
          messages.success(request, 'Shapefile upload succesful!') 
          return redirect('shapeCreated') 
         else: 
          messages.error(request, 'Something went wrong uploading Shapefile.') 
        else: # request.method == 'GET' 
         form = UploadForm(initial={'user': request.user}) 
        return render_to_response('my_app/base_shapeIngestion.html', 
               {'form': form}, 
               context_instance=RequestContext(request)) 
    
+0

嘗試不將'request.FILES'傳遞給'UploadForm'。僅用於處理程序。 – 2013-04-24 14:07:12

+0

如果我這樣做了,即使我選擇了一個要上傳的字段,'is_valid()'方法也不能滿足,並且我在頁面上正確地獲得了「此字段是必需的」消息。 – caneta 2013-04-29 11:19:26

回答

0

將您的查看功能更改爲:

def testupload2(request): 
    if request.method == 'POST': 
     file_name=request.FILES['file'] 
    form = SomeForm(request.POST, request.FILES) 
    if form.is_valid(): 
     dest_file = open('C:/prototype/upload/'+ str(file_name), 'wb+') 
     path = 'C:/prototype/upload/'+ str(file_name) 
     for chunk in request.FILES['file'].chunks(): 
      dest_file.write(chunk) 
     dest_file.close() 

    t = get_template("testupload2.html") 

    lst = os.listdir('C:/downloads/prototype/prototype/upload/') 

    html = t.render(Context({'MEDIA_URL':'http://127.0.0.1:8000/site_media/'})) 
    return HttpResponse(html) 
+0

'to_json'和'arr'變量的用途是什麼?如果不使用'form.save()',如何保存表單的其他4個元素?爲什麼要使用'HttpResponse'? – caneta 2013-04-29 11:24:22

+0

@caneta我在寫這個答案的時候,在我的項目中使用了這兩個功能,我忘了刪除它們 – 2013-04-29 11:29:54

+0

好的......那麼從窗體中保存的其他元素呢? – caneta 2013-04-29 11:30:53