send blob to python flask and then save it - javascript

So I'm trying to make a website that record your voice, the problem is that when I send to a flask server the blob file or the blob url, my flask python code says that is no content while it is, how can I send the blob, so the server can save it as a file.
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { type: "audio/wav" })
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
var data = new FormData()
data.append('file', audioUrl)
fetch('http://127.0.0.1:5000/receive', {
method: 'POST',
body: data
}).then(response => response.json()
).then(json => {
console.log(json)
});
and my python flask code:
#app.route("/receive", methods=['post'])
def form():
files = request.files
file = files.get('file')
print(file)
with open(os.path.abspath(f'backend/audios/{file}'), 'wb') as f:
f.write(file.content)
response = jsonify("File received and saved!")
response.headers.add('Access-Control-Allow-Origin', '*')
return response
is there a way to do it? send record blob file, download it into python?

The problem is in this line:
data.append('file', audioUrl)
you don't use FormData.append the right way.
it should be:
data.append('file', audioBlob , 'file')
See documentation: https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

Related

how to send mp3 blob as a post request?

I have an audio recorder and i need to send it as a post request in a third party server so it must be mp3.
My blob logs :
size:17981
type: "audio/webm;codecs=opus"
and my code :
async function sendBlob() {
const formData = new FormData();
formData.append("audio-file", getBlob);
const res = await fetch("/api/whisper", {
method: "POST",
// headers: {
// "Content-Type": `multipart/form-data`,
// },
body: formData,
});
const { result } = await res.json();
}
I already tried to create a File() and almost everything, i need to send it as a mp3 file.
I tried to send the blob, to append it in a FormDat() and in a File(), i tried to send the url but the post request only accepts mp3 files (if i upload the file and send it works, but i want to record and send direct)

multipart/form-data not being automatically set with axios in React Native

When attempting to upload a file to Amazon S3 using axios, I have been encountering a very strange issue. Normally, in a web browser, when FormData has binary data in it, the Content-Type header automatically gets set to multipart/form-data; boundary=<some random string>. However, I have been completely unable to achieve that in React Native (testing on an iOS device). The Content-Type is automatically set to application/json, and thus not being detected as a correctly formatted body when uploading to Amazon S3. I have tried specifying a blob in the file parameter in FormData instead of the URI to the file as well to no avail. I have appended my code below, any advice would be very much appreciated.
const uploadFileToS3 = (
presignedPostData,
file) => {
// create a form obj
const formData = new FormData();
// append the fields in presignedPostData in formData
Object.keys(presignedPostData.fields).forEach(
key => {
formData.append(
key,
presignedPostData.fields[key],
);
},
);
// append the file and uplaod
const getBlob = async () => {
const img_url = previewPath;
let result = await fetch(img_url);
const blob = await result.blob();
formData.append('Content-Type', 'image/jpeg');
formData.append('file', {
uri: previewPath,
type: 'image/jpeg',
name: 'test.jpeg',
});
console.log(formData, 'wild');
// post the data on the s3 url
axios
.post(presignedPostData.url, formData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error.response);
});
};
getBlob();
};

Send Audio File with axios

How to send an audio file to an API with Axios?
I'm programming in JavaScript - React Native and I'm stuck on that part.
I want to know how I do this through a script running with node, not html.
var audioFile = fs.createReadStream("./Welcome.wav")
var form = new FormData();
form.append("file", audioFile);
axios.post('https://speech2text-vitor.herokuapp.com/name',
form,
{
headers: {
"Content-Type": "multipart/form-data"
}
}
)
.then(result => {
console.log(result.data)
})
Note: I'm running with nodejs
API in Python:
app = FastAPI()
#app.post("/name", )
async def post_name(file: UploadFile=File(...)):
return file.filename

Write a JSON data blob file to disk. What is the correct Content-Type?

I want to save a JSON file to the server using fetch() API in Javascript. The idea is to save a data blob to a folder in the served named data.
Here's my code:
function project_save_confirmed(input) {
if ( input.project_name.value !== _onco_settings.project.name ) {
project_set_name(input.project_name.value);
}
// onco project
var _onco_project = { '_onco_settings': _onco_settings,
'_onco_img_metadata': _onco_img_metadata,
'_onco_attributes': _onco_attributes };
var filename = input.project_name.value + '.json';
var data_blob = new Blob( [JSON.stringify(_onco_project)],
{type: 'text/json;charset=utf-8'});
//save_data_to_local_file(data_blob, filename);
upload_json_to_server(data_blob, filename);
user_input_default_cancel_handler();
}
async function upload_json_to_server(data_blob, filename) {
const response = await fetch('https://localhost:3000/api/json', {
method: 'POST',
body: data_blob,
headers: {
'Content-Type': 'text/json'
}
});
const myJson = await response.json();
console.log(myJson);
}
I pass the JSON data blob to the upload function and then I want to make a POST API call to save that data blob to disk and save it as filename.json.
I guess I'm failing on the Content Type. Is there anything like 'Content-Type': 'file/json'?
Kind regards

Download and upload image without saving to disk

Using Node.js, I am trying to get an image from a URL and upload that image to another service without saving image to disk. I have the following code that works when saving the file to disk and using fs to create a readablestream. But as I am doing this as a cron job on a read-only file system (webtask.io) I'd want to achieve the same result without saving the file to disk temporarily. Shouldn't that be possible?
request(image.Url)
.pipe(
fs
.createWriteStream(image.Id)
.on('finish', () => {
client.assets
.upload('image', fs.createReadStream(image.Id))
.then(imageAsset => {
resolve(imageAsset)
})
})
)
Do you have any suggestions of how to achieve this without saving the file to disk? The upload client will take the following
client.asset.upload(type: 'file' | image', body: File | Blob | Buffer | NodeStream, options = {}): Promise<AssetDocument>
Thanks!
How about passing the buffer down to the upload function? Since as per your statement it'll accept a buffer.
As a side note... This will keep it in memory for the duration of the method execution, so if you call this numerous times you might run out of resources.
request.get(url, function (res) {
var data = [];
res.on('data', function(chunk) {
data.push(chunk);
}).on('end', function() {
var buffer = Buffer.concat(data);
// Pass the buffer
client.asset.upload(type: 'buffer', body: buffer);
});
});
I tried some various libraries and it turns out that node-fetch provides a way to return a buffer. So this code works:
fetch(image.Url)
.then(res => res.buffer())
.then(buffer => client.assets
.upload('image', buffer, {filename: image.Id}))
.then(imageAsset => {
resolve(imageAsset)
})
well I know it has been a few years since the question was originally asked, but I have encountered this problem now, and since I didn't find an answer with a comprehensive example I made one myself.
i'm assuming that the file path is a valid URL and that the end of it is the file name, I need to pass an apikey to this API endpoint, and a successful upload sends me back a response with a token.
I'm using node-fetch and form-data as dependencies.
const fetch = require('node-fetch');
const FormData = require('form-data');
const secretKey = 'secretKey';
const downloadAndUploadFile = async (filePath) => {
const fileName = new URL(filePath).pathname.split("/").pop();
const endpoint = `the-upload-endpoint-url`;
const formData = new FormData();
let jsonResponse = null;
try {
const download = await fetch(filePath);
const buffer = await download.buffer();
if (!buffer) {
console.log('file not found', filePath);
return null;
}
formData.append('file', buffer, fileName);
const response = await fetch(endpoint, {
method: 'POST', body: formData, headers: {
...formData.getHeaders(),
"Authorization": `Bearer ${secretKey}`,
},
});
jsonResponse = await response.json();
} catch (error) {
console.log('error on file upload', error);
}
return jsonResponse ? jsonResponse.token : null;
}

Categories

Resources