1

In my project I use Flask framework and JS on the front end, now I want to use AJAX post method to send a image to server side and save the image.
So far, based on some searching, I use FileReader() API to read the file in and generate a thumbnail on the web, this part can work well now. Then I want to continue sending the image to the server, but blocked here. I use $.AJAX post method to send the image.
the js function goes as following:

var files = [];
function handleFileSelect(event) {
    var selectedFile = event.target.files[0];
    var reader = new FileReader();
    var imgtag = document.getElementById("currentImage");
    imgtag.title = selectedFile.name;
    reader.onload = function(event) {
      imgtag.src = event.target.result;
      object = {};
      object.filename = selectedFile.name;
      object.data = event.target.result;
      files.push(object);
    };
    reader.readAsDataURL(selectedFile);
 };

$(document).ready(function(){
    $("form").submit(function() {
        alert("good");
        $.each(files, function(index, file) {
        $.ajax({url: "/image",
            type: 'POST',
            data: {filename: file.filename, data: file.data},
        });      
     });
     });
}); 

and since I don't know how to handle and get the image file, so the server side code I just try request.files as following:

@app.route('/image',methods=['POST'])
def image_upload():
    file = request.files['files']
    print file.filename

I debug that the '/image' can get the post request, but have no idea about how to get the image from request.

Edit: the HTML form part goes as following:

<form enctype="multipart/form-data">
<input type="file" id="files" name="files"  onchange="handleFileSelect(event)"/>
<img id="currentImage" src="/static/1.jpg" alt="Mountain View" style="width:304px;height:228px;">
<input type="submit" value="Analyse the image v2">
</form>

Edit II: Find the solution in other ticket, the FormData object is the right answer in the following link: How to upload a file using an ajax call in flask

Community
  • 1
  • 1
Chris Bao
  • 2,418
  • 8
  • 35
  • 62
  • it's a long shot that this will work: `if request.method == 'POST': file = request.files['file']` – wgwz Feb 28 '16 at 20:16
  • you might want to add this to your form: `enctype=multipart/form-data` (another long shot) – wgwz Feb 28 '16 at 20:20
  • @wgwz, I tried, but no difference. I post the HTML tags here as well. Already, add the `enctype=multipart/form-data` – Chris Bao Feb 29 '16 at 01:10
  • break your problem into a simpler example. that's the best i can tell you. you've got a lot of components there and no real specific error messages. http://stackoverflow.com/help/mcve – wgwz Feb 29 '16 at 03:55

0 Answers0