'How to send Image from front end ajax to Flask Restful api
I have created an API using Flask Restful in which the user can send a gemstone image and in return, he/she will receive a JSON with image name prediction.
My Flask Code is below
class Predict(Resource):
def get(self):
image = request.files['image']
image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))
file_path = app.config['IMAGE_UPLOADS'] + "/" + image.filename
prediction = {"pred": predict(file_path)}
return jsonify(prediction)
api.add_resource(Predict, '/image')
predict is the function that takes the image path saved locally on the server.
when I use to test the API from python code i.e.
from requests import get
url = "http://127.0.0.1:5000/image"
img = open('./static/uploads/img.PNG', 'rb')
my_img = {'image': img}
pred = get(url, files=my_img)
print(pred.text)
it's work fine and I know in python code the image is an Object of type BufferedReader.
now I want to accept the file from the webform using ajax and formData. When I submit the form it returns 400 Bad Request
The Ajax Function which I used in my code
<form id="myform">
<input type="file" name="image" id="image">
<input type="submit" value="Submit">
</form>
<script src="../static/js/ajax.js"></script>
<script>
let form = document.querySelector("#myform");
form.addEventListener("submit", e => {
e.preventDefault();
formdata = new FormData(form);
ajax({
url: "http://127.0.0.1:3000/image",
method: "GET",
data: formdata,
onsuccess: (responseText, status, statusText)=>{
console.log(responseText);
console.log(status);
console.log(statusText);
},
onfailure: (status, statusText)=>{
console.log(status);
console.log(statusText);
},
contentType: false,
});
})
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
