Django ajax file upload

后端 未结 2 1454
迷失自我
迷失自我 2021-01-01 08:39

So I am trying to upload a file without any external plugins, but I am running into some errors.

                
相关标签:
2条回答
  • 2021-01-01 09:09

    Here is what I use to upload files using javascript, hope this helps ! Just pass your $('#file') as a parameter.

    function upload(field, upload_url) {
        if (field.files.length == 0) {
            return;
        }
        file = field.files[0];
        var formdata = new FormData();
        formdata.append('file_upload', file);
        $.ajax({
            url: upload_url,
            type: 'POST',
            data: formdata,
            processData: false,
            contentType: false,
            success: console.log('success!')
        });
    }
    

    [EDIT]

    And this is what I do on the server side (simplified):

    def save_file(dest_path, f, filename):
        original_name, file_extension = os.path.splitext(f.name)
        filename = filename + '-' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + file_extension
        url = '/' + dest_path + '/' + filename
        path = django_settings.MEDIA_ROOT + url
        destination = open(path, 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
        return path
    
    class FileUploadView(View):
        def post(self, request, *args, **kwargs):
            if request.FILES and request.FILES.get('file_upload'):
                path = save_file(UPLOAD_TO, 
                                 request.FILES.get('file_upload'), 
                                 FILENAME)
            return self.render_to_response({})
    
    0 讨论(0)
  • 2021-01-01 09:14

    i followed this tutorial http://www.script-tutorials.com/pure-html5-file-upload/ and in the php part i replaced with :

    class UploadImageView(LoginRequiredMixin, CurrentUserIdMixin, View):
    
        @method_decorator(csrf_protect)
        def dispatch(self, *args, **kwargs):
            return super(UploadImageView, self).dispatch(*args, **kwargs)
    
        def post(self, request, username):
            path = 'myproject/media/pictures/guitar.jpg'
            f = request.FILES['image_file']
            destination = open(path, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
                destination.close()
    
                return HttpResponse("image uploaded")
    

    also changed this lines

    <form id="upload_form" enctype="multipart/form-data" method="post" action=".">
                                    {% csrf_token %}
    
    0 讨论(0)
提交回复
热议问题