Seite 1 von 1

Flask upload file

Verfasst: Samstag 11. Juni 2022, 20:38
von ChristophS
Hallo Zusammen

Ich möchte eine Datei (img, mp3, mp4 ...) uploaden und komme nicht weiter.

Die Datei wähle ich mich mit einem <input type=file> aus und rufe folgende Funktion mit onchange() auf. Das scheint soweit zu funktionieren.

Code: Alles auswählen

   
    function upload(fileInput){    
      console.log(fileInput.files[0])       
      file = fileInput.files[0]              
      $.ajax({
        type: "POST",
        url: '/upload',
        enctype: "multipart/form-data",
        contentType: "application/json",
        data: file.slice,
        dataType: "json",
        success: function (response){console.log(response)}         
      });         
    }      
Auf der Serverseite habe ich folgenden Code zum testen:

Code: Alles auswählen

@app.route('/upload', methods = ['POST'])
def upload():
    data = request.files.get('file')
    print(data)
    return ('data')
Die Ausgabe ist immer None, es scheint, dass die Daten nie ankommen.

Weiss jemand Rat?

Re: Flask upload file

Verfasst: Samstag 11. Juni 2022, 21:11
von Sirius3
Du überträgt die Daten Deiner Datei direkt, weder als json noch als Formdata, obwohl Du beides verwirrenderweise gleichzeitig angibst. Logisch, dass Flask das nicht als files interpretieren kann.

Re: Flask upload file

Verfasst: Sonntag 12. Juni 2022, 09:12
von ChristophS
Danke für den Hinweis. Er hat mich schon näher an das Ziel gebracht.

Code: Alles auswählen

      image = fileInput.files[0]

      $.ajax({
        type: "POST",
        url: '/upload',
        contentType: "application/json",
        dataType : 'json',
        data: JSON.image,
        dataType: "json",
        success: function (response){console.log(response)}         
      });
[code]

Das Resultat ist: ImmutableMultiDict([]).