i want to save my csv file in database using flask. in frontend i wrote a function to send the csv file to backend. here is the code:
saveCsvFile = () => {
console.log('saveCsvFile ...', this.state.csvFile);
axios.post( this.state.apiUrl+'/api/v1/SalesLead/saveCsv', {
'csv_file':this.state.csvFile,
}, {} )
};
<form>
<input onChange={this.fileHandler} type="file" accept=".csv,text/csv" />
<button onClick={() => this.saveCsvFile()} type="submit" form="form1" value="Submit">Submit</button>
</form>
And i wrote a simple function to read the csv file in python(flask). here is the code:
@SalesLeadController.route('/saveCsv', methods=['POST'])
def upload_csv():
print('upload_csv')
if request.method == 'POST':
csv_file = request.files['file']
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
user = SalesLead(username=row[0], email=row[1])
db.session.add(user)
db.session.commit()
return Response(json.dumps({'status': 'success', 'message': 'data successfully saved.'}), status=200, mimetype='application/json')
But i am getting this error after uploading the CSV file:
400 Bad Request: KeyError: 'file'
How can i solve this error?
<form>
<input onChange={this.fileHandler} type="file" accept=".csv,text/csv" name = "file" />
</form>
Since you are doing,
csv_file = request.files['file']
Here the string 'file' is the key, where the value is the actual file uploaded. The key is the name specified in the input tag in HTML
我认为您忘了在表单上添加属性: enctype="multipart/form-data"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.