How to load audio file into html page - javascript

I have backend with flask and for frontend I used javascript-html, when I use postman or insomnia and send the request to get the audio file it's working and it show the audio file and I can play it, but when I try to use it on HTML-javascript not working
this is my flask part
#app.route('/g-media', methods=['POST'])
def get_media():
file = request.get_json()['id']
dict_data = get_media_path(file)
return send_file(dict_data['path'], mimetype="audio/wav", as_attachment=True)
and this is my javascript part
async function get_selected_detail(audio_id) {
var url = 'http://127.0.0.1:5000/g-media';
var data = JSON.stringify({"id": audio_id});
var header = {
'Content-Type': 'application/json',
}
let result = await axios.post(url, data, { headers: header }).then(res => {
console.log(typeof(res.data))
this is HTML part
<audio controls>
<source type="audio/mpeg" id="audio-ource">
</audio>

The "source" tag expects src which is a path to the target file/input you need to create a URL while uploading the file and send that URL back via get call.
i.e. <source type="audio/mpeg" src="path to your file" id="audio-ource"/ >

Related

React unable to download PDF from anchor tag

I'm trying to download a document with react. I have this in my code right now:
<li><a href={this.state.invoice.pathToFile}>Download Invoice</a></li>
The path to the file looks like this:
C:\bin\documents\invoices\invoice-01-01-2021.pdf
Everytime we click the link to download the file, We are sent back to the homepage. I would expect it to just download the file. When I hover over the download link it does display the file location:
Not sure what's going on or causing this.
This is not a react issue. Add the download attribute to the anchor <a> so that the browser will download the file
<li><a href={this.state.invoice.pathToFile} download>Download Invoice</a></li>
You can use download attribute to the anchor element to save files, if you reference the file correctly, like this:
<a href="Your file location" download>Download</a>
And in your case it should be like this:
<li><a href={this.state.invoice.pathToFile} download>Download Invoice</a></li>
Neither of these solutions ended up working. On the back-end I had to implement a downloads controller like so:
[HttpPost]
public ActionResult GetInvoiceDocument([FromBody] string PathToFile)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(PathToFile);
var fileName = PathToFile.Split("/")[3];
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
On the front-end I created an method that gets called onClick. This downloads a document and then appends an anchor tag to the DOM and instantly downloads the file.
downloadFile = (e : any, filePath : string) => {
e.preventDefault();
let options = {
method : "POST",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json;charset=UTF-8'
},
body : JSON.stringify(filePath)
};
fetch('https://localhost:44304/api/DownloadDocument', options).then(async res => ({
filename: this.state.invoice.pathToFile!.split('/')[3]!,
blob : await res.blob()
})). then(resObj => {
const newBlob = new Blob([resObj.blob], { type : 'application/pdf'});
const objUrl = window.URL.createObjectURL(newBlob);
let link = document.createElement('a');
link.href = objUrl;
link.download = resObj.filename;
link.click();
setTimeout(() => { window.URL.revokeObjectURL(objUrl); }, 250);
})
}

Record Video using Media capture cordova plugin and upload to remote server issue

I am working on cordova application in which i need to capture video or choose from gallery and upload it to the remote server. I have captured the video and it path is coming but i'm not able to see the video with url and impossible to send it to server too
`
takeVideo() {
let options: CaptureVideoOptions = { limit: 1, duration: 15 }
this.mediaCapture.captureVideo(options)
.then(
(data: MediaFile[]) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
// let base64Image = 'data:image/jpeg;base64,' + imageData;
// alert(data[0].fullPath)
// this.copyFileToLocalDir(data[0].fullPath);
alert(data[0].fullPath)
this.dispVideos.push(data[0].fullPath)
},
(err: CaptureError) => {
alert(err)
}
);
}
`
UPLOAD METHOD
upload method
html
<div *ngIf="dispVideos?.length > 0">
<video #myVideo preload="metadata" controls="false">
<source [src]="sanitizer.bypassSecurityTrustResourceUrl(dispVideos[0])" type="video/mp4">
</video>
</div>
to display the video you have to insert
this.dispVideos.push((window as any).Ionic.WebView.convertFileSrc(data[0].fullPath));
I also recently found an error on ios with the apache cordova camera plugin it provides the temporary path to the video file to come out from this error implement below changes in camera plugin.
in CDVCamera.m change THIS:
(CDVPluginResult*)resultForVideo:(NSDictionary*)info
{
NSString* moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] absoluteString];
return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:filePath];
}
to THIS:
(CDVPluginResult*)resultForVideo:(NSDictionary*)info
{
NSString* moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSArray* spliteArray = [moviePath componentsSeparatedByString: #"/"];
NSString* lastString = [spliteArray lastObject];
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:lastString];
[fileManager copyItemAtPath:moviePath toPath:filePath error:&error];
return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:filePath];
}

angularjs can't show file from api

I have an app where frontend is developed in angularjs and backend with symfony.
I need to have a route like: http://example.com/api/invoices/file?file=foo
So I have this inside my FileController:
/**
* Matches /invoices/file/{filename} exactly
*
* #Route("/invoices/file/{filename}", name="get_invoice_file")
*/
public function getInvoiceFileAction(string $filename, Request $request)
{
$path = $this->get('kernel')->getRootDir() . '/../web/uploads/invoices/' . $filename;
if (!file_exists($path)) {
return new Response('file not found', 404);
}
$file = file_get_contents($path);
$headers = [
'Content-Type' => 'application/pdf',
'Conteng-Length' => filesize($path)
];
return new Response($file, 200, $headers);
}
Inside my angularjs app I have this to get the response inside my frontend controller:
vm.getInvoices = function() {
vm.loading = true;
apiResolver.resolve('invoices.documents.file#get', { "file": vm.searchFile }).then(function(response) {
vm.loading = false;
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
vm.file = $sce.trustAsResourceUrl(fileURL);
});
};
Into my html I have this:
<embed ng-src="{{vm.file}}" style="width:200px;height:200px;"></embed>
When I render the page I see a 200response so the file exist but into the html I have an empty space instead of pdf file.
Inside embed tag there is this:
<embed style="width:200px;height:200px;" ng-src="blob:http://localhost:3000/d32d87d1-6582-42e3-85ae-dc174ca5a473" src="blob:http://localhost:3000/d32d87d1-6582-42e3-85ae-dc174ca5a473">
If I copy url inside a browser returns me that can't load file.
Backend and frontend are in different folder and the pdf CAN'T be viewed by a public link infact these pages are protected with jwt system.
How can I show inside my page the pdf?
What I'm doing wrong?
Make sure that JWT Authorization Token is passed in the request . If not , pass it in the Blob object.
If token is passed try replacing embed to object as mentioned below :
<object data="{{vm.file}}" style="width:200px;height:200px;" type="application/pdf"></object>

Angularjs Code to display Pdf file in google chrome is not working but working for firefox

Below code to display Pdf file in google chrome is not working but working in firefox.
HTML View
<div>
<object ng-bind="pdfcontent" data="{{pdfcontent}}" type="application/pdf" width="100%" height="800px">
</object>
</div>
Angularjs Code
$http.get('/myurl/', {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.pdfcontent = $sce.trustAsResourceUrl(fileURL);
});
I am getting below two errors
firebug-lite.js:18877 Uncaught InvalidStateError: Failed to read the
'responseText' property from 'XMLHttpRequest': The value is only
accessible if the object's 'responseType' is '' or 'text' (was
'arraybuffer').(anonymous function) # firebug-lite.js:18877
jquery.js:2812 GET http://abc123.com/%7B%7Bpdfcontent%7D%7D 404 (Not
Found)
What is wrong in my code, how to to fix this, any help is appreciated.
Thanks.
you problem is that the data attribute is binded once the object is been been rendered and therefore when your request response the pdfcontent isn't been binded
to solve this you can do two think
using a directive for this purpose like in this answer
you can use an if statement like in the snippet below
$scope.downloaded = false
$http.get('/myurl/', {responseType: 'arraybuffer'}).success(function (data) {
$scope.downloaded = true
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.pdfcontent = $sce.trustAsResourceUrl(fileURL);
});
<div ng-if="downloaded">
<object ng-bind="pdfcontent" data="{{pdfcontent}}" type="application/pdf" width="100%" height="800px">
</object>
</div>

AngularJS - Disabling the PDF print/download bar when displaying PDF in browser. Converting PDF to Images?

I am exposing a PDF file in the browser like:
//html
<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 550px;"></object>
//angular controller
$http.get('/api/,
{ responseType: 'arraybuffer' })
.success(function (response) {
var file = new Blob([(response)], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
This works fine getting the Stream/Blob of the PDF back and exposing it in the browser, but I wish to not show the print/download/rotate bar that is shown at the top:
Any idea how this can be achieved? If I have to convert the PDF to a series of images is there a good way to do that from a BLOB form either on my client or server side?

Categories