Wenn ich Roh-HTML verwende, um eine Datei auf einem flask Server zu veröffentlichen, kann ich über die flask request global auf Dateien zugreifen:
<form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
<input type="file" id="file" name="file">
<input type=submit value=Upload>
</form>
In der Flasche:
def post(self):
if 'file' in request.files:
....
Wenn ich das Gleiche mit Axios versuche, ist die flask request global leer:
<form id="uploadForm" enctype="multipart/form-data" v-on:change="uploadFile">
<input type="file" id="file" name="file">
</form>
uploadFile: function (event) {
const file = event.target.files[0]
axios.post('upload_file', file, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
Wenn ich die gleiche uploadFile - Funktion wie oben verwende, aber die Header json aus der axios.post - Methode entferne, erhalte ich im Formularschlüssel meines flask request object eine CSV - Liste mit Zeichenfolgenwerten (file is a. csv).
Wie kann ich ein Dateiobjekt über Axios senden lassen?
Fügen Sie die Datei einem formData
Objekt hinzu und setzen Sie das Content-Type
Header zu multipart/form-data
.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Beispielanwendung mit Vue. Erfordert einen Backend-Server, der auf localhost ausgeführt wird, um die Anforderung zu verarbeiten:
var app = new Vue({
el: "#app",
data: {
file: ''
},
methods: {
submitFile() {
let formData = new FormData();
formData.append('file', this.file);
console.log('>> formData >> ', formData);
// You should have a server side REST API
axios.post('http://localhost:8080/restapi/fileupload',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
console.log('SUCCESS!!');
})
.catch(function () {
console.log('FAILURE!!');
});
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
console.log('>>>> 1st element in files array >>>> ', this.file);
}
}
});