【问题标题】:rename file with django-ajax-uploader使用 django-ajax-uploader 重命名文件
【发布时间】:2016-05-22 21:19:59
【问题描述】:

我正在使用https://github.com/skoczen/django-ajax-uploader 在 django 中上传文件。它可以工作,但我想在此过程中重命名上传的文件。我想添加一个时间戳,所以我确定它有一个唯一的名称。

怎么做?

【问题讨论】:

    标签: ajax django file upload


    【解决方案1】:

    我最终使用了jQuery-File-Upload。它允许在视图中定义文件的路径。示例:

    urls.py

    url(r'^upload_question_photo/$', UploadQuestionPhoto.as_view(), name="upload_question_photo"),
    

    index.html

    var input=$(this).find("input");
    var formData = new FormData();
    formData.append('photo', input[0].files[0]);
    formData.append('question', input.attr("name"));
    formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    input.fileupload(
    {
        dataType: 'json',
        url: "{% url 'campaigns:upload_question_photo' %}",
        formData: formData,
    
        //the file has been successfully uploaded
        done: function (e, data) 
        {
            response=data.result;
            window.console&&console.log("Successfully uploaded!");
            window.console&&console.log(response.path);
        }.bind(this),
    
        processfail: function (e, data) 
        {
            window.console&&console.log('Upload has failed');
        }.bind(this)
    });
    

    views.py

    class UploadQuestionPhoto(View):
        u"""Uploads photos with ajax 
        Based on the code  #https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/blob/master/upload/views.py
        """
    
        def post(self, request, *args, **kwargs):
            print "UploadQuestionPhoto post"
            response={}
    
            question=str(request.POST["question"])       
            #path where the file is going to be stored
            path="/question/" + question + "/"
            photo_path=settings.MEDIA_ROOT + path
    
            # if 'f' query parameter is not specified -> file is being uploaded
            if not ("f" in request.GET.keys()):
                print "file upload"
                # make sure some files have been uploaded
                if request.FILES:
                    # get the uploaded file
                    photo_file = request.FILES["question_field_" + question]
                    name_with_timestamp=str(time.time()) + "_" + photo_file.name
    
                    # create directory if not exists already
                    if not os.path.exists(photo_path):
                        os.makedirs(photo_path)
    
                    # add timestamp to the file name to avoid conflicts of files with the same name
                    filename = os.path.join(photo_path, name_with_timestamp)
                    # open the file handler with write binary mode
                    destination = open(filename, "wb+")
                    # save file data with the chunk method in case the file is too big (save memory)
                    for chunk in photo_file.chunks():
                        destination.write(chunk)
                    destination.close()
    
                    #response sent back to ajax once the file has been successfuly uploaded
                    response['status']='success'
                    response["path"]=photo_path+name_with_timestamp
    
    
            # file has to be deleted (TODO: NOT TESTED)
            else: 
                # get the file path by getting it from the query (e.g. '?f=filename.here')
                filepath = os.path.join(photo_path, request.GET["f"])
                os.remove(filepath)
                # generate true json result (if true is not returned, the file will not be removed from the upload queue)
                response = True
    
            # return the result data (json)
            return HttpResponse(json.dumps(response), content_type="application/json")
    

    瞧!希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 2013-04-26
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2016-05-29
      相关资源
      最近更新 更多