1

When the user uploads a file, I want it to store the file, read the first 10 rows and send the first 10 rows back to the page. I'm not sure how to go about doing this in the views or on the client side.

def UploadTest(request):
    if request.POST and request.FILES:
        csvfile = request.FILES['csv_file']
        dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024))
        csvfile.open()
        reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect)
    return render(request, 'index.html', {"form": reader} )

That is what I have in my views.py right now. But I don't want it to render a new page.

ALUW
  • 397
  • 1
  • 5
  • 15
  • Use Ajax instead if you don't want to render a page. Make it so that your template makes the ajax call and the backend will return a JSON of the 10 first rows. Use the JSON result and format it as needed and display it to the user using JS. – Algorithmatic Apr 12 '17 at 21:43
  • I understand what you are saying but Im still confused as to how to accomplish that – ALUW Apr 12 '17 at 22:04

1 Answers1

0

Use FormData to get file data from form, and send an Ajax call.

Something like the following:

function upload(event) {
    event.preventDefault();
    var myFile = new FormData($('form').get(0));

    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: myFile,
        cache: false,
        processData: false,
        contentType: false,
        success: function(data) {
            # your logic here
        }
    });
    return false;
}

$(function() {
        $('myForm').submit(upload);
});
Algorithmatic
  • 1,824
  • 2
  • 24
  • 41