Flast is receiving ImmutableMultiDict([]).
My Html Code
const audioChunks = [];
mediaRecorder.addEventListener("dataavailable", event => {
audioChunks.push(event.data);
});
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
console.log(audioBlob)
var myHeaders = new Headers();
myHeaders.append("Content-Type", "audio/wave");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: audioBlob,
redirect: 'follow'
};
My Flask Code
#app.route('/stt',methods=['GET','POST'])
def STT():
app.logger.warning("request.files: {0}".format(request.files))
f = request.files['audio-blob']
print(f)
file_obj = io.BytesIO() # create file-object
file_obj.write(f.read()) # write in file-object
file_obj.seek(0) # move to beginning so it will read from beginning
r = sr.Recognizer()
mic = sr.AudioFile(file_obj) # use file-object
with mic as source:
audio = r.record(source)
result = r.recognize_google(audio_data=audio, language="en-US", show_all=True)
return jsonify(text=result )
Not able to understand the error.
How to post Blob file from html and received in Flask Post APIs.
Please Help me out on this problem.
Thank You
Related
I am trying to send some data from the client side (react native) that includes a few images so I append them to formdata and successfully send it through a post request but I am having trouble figuring out how to handle it on the server side.
My react code:
const post = async () => {
const token = await getToken();
const [description, setDescription] = useState('');
const formData = new FormData();
images.forEach((image) => {
formData.append(`images`, {
uri: image,
type: 'image/jpeg',
name: image,
});
});
formData.append('description', description);
console.log('formdata:', formData);
try {
await axios.post(URL, formData._parts, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: token,
},
});
} catch (e) {
console.log(e);
}
};
when i console log formData._parts on client side i get:
formdata: [["images", {"name": "/Library/Developer/CoreSimulator/Devices/123.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/123.jpg"}], ["images", {"name": "/Library/Developer/CoreSimulator/Devices/456.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/456.jpg"}], ["description", "Test"]]
It post request only works whenn i send formData._parts but not when i send just formData
on my server side (django/drf):
models.py:
class Post(models.Model):
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, default=None
)
images = models.FileField(
max_length=3000, default=None, null=True, blank=True, upload_to='media/post_images')
description = models.TextField(null=False, default=None)
date = models.DateTimeField(editable=False, auto_now_add=True)
serializers.py:
class PostSerializer(serializers.ModelSerializer):
images = serializers.FileField()
class Meta:
model = Post
fields = "__all__"
views.py
class PostView(APIView):
serializer_class = PostSerializer
parser_classes = (MultiPartParser, FormParser)
def post(self, request, format=None):
form_data = request.data
images = form_data.get('images')
description = form_data.get('description')
user_id = self.request.user
print(form_data)
post = Post.objects.create(
images=images, description=description, user_id=user_id)
post.save()
serializer = PostSerializer(post)
return Response(serializer.data, status=status.HTTP_201_CREATED)
when i print the form_data in python i get:
<QueryDict: {'0': ['images'], '1.uri': ['/Library/Developer/CoreSimulator/Devices/123.jpg'], '1.type': ['image/jpeg'], '1.name': ['/Library/Developer/CoreSimulator/Devices/123.jpg'], '1.0': ['images'], '1.1.uri': ['/Library/Developer/CoreSimulator/Devices/456.jpg'], '1.1.type': ['image/jpeg'], '1.1.name': ['/Library/Developer/CoreSimulator/Devices/456.jpg'], '2.0': ['description'], '2.1': ['Test']}>
How can i extract the data and save it to the database?
Django is handling that for you. You can try to access your images with:
request.FILES.getlist("images")
This will give you a list of all the images that are found in the submitted form.
EDIT:
For the Backend actually being able to read the data, it obviously also has to be send. To append the data you can use something like this:
var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});
I'm querying a dreambooth model from Hugging Face using the inference API and am getting a huge data response string back which starts with: ����çx00çx10JFIFçx00çx01çx01çx00çx00çx01çx0...
Content-type is: image/jpeg
How do I decode this and display it as an image in javascript?
Not 100% sure but I suppose something similar to that should do it.
for (var e = atob("����çx00çx10JFIFçx00çx01çx01çx00çx00çx01çx0..."), t = new Array(e.length), r = 0; r < e.length; r++) t[r] = e.charCodeAt(r);
var n = new Uint8Array(t),
a = new Blob([n], {
type: "image/jpeg"
}),
x = (window.URL || window.webkitURL).createObjectURL(a);
let img = document.createElement("img")
img.src = x;
got it working by including a responseType param in the axios request.
Node.js code:
const inputData = {
inputs: prompt,
options: {
wait_for_model: true,
},
}
const response = await axios({
url: `https://api-inference.huggingface.co/models/${model}`,
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.HUGGING_FACE_TOKEN}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
data: JSON.stringify(inputData),
responseType: 'arraybuffer',
})
const mimeType = response.headers['content-type']
const result = response.data
const base64data = Buffer.from(result).toString('base64')
const img = `data:${mimeType};base64,` + base64data
return img
React code:
<img src={img} />
Hi I have a backend which receive a request with a picture and storage, I try it with postman and with the code below and works perfectly
var axios = require('axios')
var FormData = require('form-data')
var fs = require('fs')
var data = new FormData()
data.append('file', fs.createReadStream('index.png'))
console.log('HEADERS')
console.log(data.getHeaders())
let config = {
method: 'post',
url: 'http://localhost:5013/v1/business/honda/widget/test/',
headers: {
...data.getHeaders(),
},
data: data,
}
The problem is in my vue app I try to do it with the next code, I have 2 buttons with one load the image and the other to send it.
In the back end I have the follow error when try to pick 'file'
http: no such file
let imageData
//send the image to backend
function funtest() {
console.log('image')
const formData = new FormData()
const url = 'http://localhost:5013/v1/business/honda/widget/test/'
formData.append('file', imageData)
let config = {
method: 'post',
url: url,
headers: {
'Content-type': 'multipart/form-data',
},
data: formData,
}
axios(config)
.then((response) => {
console.log('RESPONSE')
console.log(response)
})
.catch((error) => {
console.log('ERROR')
console.log(error)
})
}
//function to read the image
function onImage(data) {
const reader = new FileReader()
reader.onload = (e) => {
imageData = e.target.result
console.log('imagen')
}
reader.readAsDataURL(data.target.files[0])
}
I think it's probably not reading the path to index.png file correctly here, fs.createReadStream('index.png')
Consider using path like this
const path = require('path');
const filePath = path.join(__dirname, 'index.png');
data.append('file', fs.createReadStream(filePath))
NB: This is just a quick and dirty suggestion, and it's not guaranteed to work but it's definitely worth a shot
I'm using axios on server side.
I want to download big files .. technically this should be used with byte-ranges
Does axios handle the byte-range request so that the callback function is only called when all the response is ready
If 1 is not true, should I handle data chunks myself ?
In the code below :
axios({
url: params.url,
method: 'GET',
responseType: 'stream' // important
}).then(function (response) {
logger.debug('__download() : done!')
let contentType = response.headers['content-type']
let contentLength = response.headers['content-length']
var writer = new streams.WritableStream()
response.data.pipe(writer)
// ....
})
Am I supposed to wait for something like response.on('end')?
The purpose of what I'm doing is to get the size of the buffer (which I could get by writer.getBuffer())
Thanks for any hint !
I found out that to download the stream, in memory in my case, I had to wait for the event on my writer (writer.on('finished',cb) vs response.on('end', cb )) (not sure if there is something like response.on('end'))...
var stream = require('stream');
var util = require('util');
var Writable = stream.Writable;
function MemoryStream(options) {
if (!(this instanceof MemoryStream)) {
return new MemoryStream(options);
}
Writable.call(this, options); // init super
}
util.inherits(MemoryStream, Writable);
MemoryStream.prototype._write = function (chunk, enc, cb) {
var buffer = (Buffer.isBuffer(chunk)) ?
chunk :
Buffer.alloc(chunk, enc);
if (Buffer.isBuffer(this.memStore)) {
this.memStore = Buffer.concat([this.memStore, buffer]);
} else {
this.memStore = buffer
}
cb();
};
MemoryStream.prototype.toBuffer = function () {
return this.memStore
};
module.exports = MemoryStream
and then in my download function :
axios({
url: params.url,
method: 'GET',
responseType: 'stream' // important
}).then(function (response) {
logger.debug('__download() : done!')
let contentType = response.headers['content-type']
let contentLength = response.headers['content-length']
var writer = new MemoryStream()
response.data.pipe(writer)
writer.on('finish', function () {
var b = writer.toBuffer()
let computedContentLength = b.byteLength
if (!contentLength) { contentLength = computedContentLength }
return callback(null, { 'foo':'bar'})
});
})
Trying to download excel (.xlsx) file from my restAPI.
This is my code -
let headers = new Headers();
headers.append('Content-Type', 'application/vnd.openxmlformats');
this.http
.get(
`${pathToExcel}`,
{ headers: headers, responseType: ResponseContentType.Blob }
)
.subscribe((res: any) => {
let blob = new Blob([res._body], { type: 'application/vnd.openxmlformats' });
let myUrl = document.createElement('a');
myUrl.href = window.URL.createObjectURL(blob);
myUrl.download = 'Log.xlsx';
let event = document.createEvent('MouseEvent');
event.initEvent('click', true, true);
myUrl.dispatchEvent(event);
});
The file is downloaded but it's empty.
What am I missing?