E
E
ellz2019-03-10 07:20:26
Django
ellz, 2019-03-10 07:20:26

Is it possible to upload an image and use it without reloading the page?

Is it possible to upload an image and continue working on it without reloading the page?
views.py:

def uploadImage(request):
  if request.method == 'POST':		
    uploaded_file = request.FILES['photo']		
    print(uploaded_file.name)
    print(str(uploaded_file.size) + ' bytes')
  return HttpResponse('test')#пробовал убрать, но получаю ошибку - "ValueError at /upload/"

URLs.py:
url(r'upload/', app.views.uploadImage, name='uploadImage'),

upload form:
<form method="post" id="loadImageForm" name="loadImageForm" enctype="multipart/form-data" action="{%url 'uploadImage'%}">
    {% csrf_token %}
    <input type='file' id="file" name='photo' accept="image/jpeg,image/png"/>
  </form>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
ellz, 2019-03-10
@ellz

Implemented it like this in
index.js:

$(document).ready(function () {
    $('#file').change(function () {
        //var formdata = new FormData($('#loadImageForm')[0]);
        var fileInput = document.getElementById('file');
        var file = fileInput.files[0];
        var formData = new FormData();
        formData.append('photo', file);
        if (formData) {
            $.ajax({                
                url: "uploadImage",
                type: "POST",
                data: formData,
                headers: { "X-CSRFToken": getCookie("csrftoken") },
                processData: false,
                contentType: false,
                success: function () {
                    console.log('success');
                },
                error: function (error) {
                    console.log(error);
                }
            });
        }
    });

    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }
});

views.py:
def uploadImage(request):
  if request.method == 'POST':		
    form = forms.FileUploadForm(data=request.POST, files=request.FILES)
    if form.is_valid():	
      print('Done')
    else:
      print(form.errors)
  return HttpResponse('test')

Thanks to alternativshik and Sergey Gornostaev

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question