0

I've a portal in which I'm recording user audio and I am getting a blob URL and now I want to store this blob url as a file in my database. Can anyone help me with this. This is my js code

 $('#upload-read-aloud').on('submit',function(e){
        e.preventDefault();
        $.ajax({
            type : 'GET',
            cache : false,
            data : {audioUrl:audioUrl},
            url : '../upload-read-aloud-test',
            success:function(response){
                alert(response)
            }
        })  
     })

And this is my controller code

 $url = $req->audioUrl;
    $upload_dir = public_path()."/assets/";
    $audio= $url;
    $audio= str_replace('data:audio/wav;base64,', '', $audio);
    $audio = str_replace(' ', '+', $audio);
    $data = base64_decode($audio);
    $file = $upload_dir . time() . ".wav";
    $success = file_put_contents($file, $data);
    echo $success ? $file : 'Unable to save the file.';

audioUrl is the Blob url which I'm passing in my route. The file is saving into the database but the file is empty.

  • It's a bad idea to store your audio file as a ob in your database. Use a storage disk. Now, when you're still trying to save your blob, show the example code, the migration and of course the errors from laravel.log when you're trying to save – UnderDog Dec 21 '22 at 07:02
  • What database are you using? Is it PostgreSQL or MySQL/MariaDB? And what error are you getting? BTW, Before deciding to store files in the database read this - https://dba.stackexchange.com/questions/2445/should-binary-files-be-stored-in-the-database (top rated answers and comments) P.S. If you want to get answers to your question, you need to provide more details about your problem (code example, description of your problem, show the error you are getting, etc.) - https://stackoverflow.com/help/how-to-ask – Dmitry K. Dec 21 '22 at 07:07
  • I edited my code please check and please let me know the solution. – Vinay Munjal Dec 21 '22 at 07:32

1 Answers1

1

As I see you use jQuery.
So, first of all DO NOT use GET request to upload data to server, use POST request instead. And send your blob as a file. Look at - https://stackoverflow.com/a/34340245/2585154

var s = 'some string data';
var filename = 'foobar.txt';

var formData = new FormData();
formData.append('file', new File([new Blob([s])], filename));
formData.append('another-form-field', 'some value');

$.ajax({
    url: '/upload',
    data: formData,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function () {
        console.log('ok');
    },
    error: function () {
        console.log('err'); // replace with proper error handling
    } 
});

Replace /upload with path to your API method, e.g.: ../upload-read-aloud-test, replace var s = 'some string data'; with your blob data and replace var filename = 'foobar.txt'; with any meaningful filename.

Or if you want to upload file from input, look at - jQuery AJAX file upload PHP

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'upload.php', // <-- point to server-side PHP script 
        dataType: 'text',  // <-- what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // <-- display response from the PHP script, if any
        }
     });
});

Replace upload.php with path to your API method, e.g.: ../upload-read-aloud-test, replace #sortpicture with your input id.

And then access your uploaded file in Laravel:

$file = $req->file('file');
dump($file);
Dmitry K.
  • 3,065
  • 2
  • 21
  • 32
  • Can you please tell me how can i store the blob url value in input type file? – Vinay Munjal Dec 21 '22 at 08:15
  • If you want to upload a file from input then use different method, look this: https://stackoverflow.com/a/23981045/2585154 – Dmitry K. Dec 21 '22 at 08:17
  • Ok got it. But can you tell me about this line of code formData.append('another-form-field', 'some value'); – Vinay Munjal Dec 21 '22 at 08:19
  • @VinayMunjal you can safely remove this line, it's just is an example that you can send some other information with your file – Dmitry K. Dec 21 '22 at 08:20
  • CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException. Now this error is occuring. I already tried by using @csrf. Can you tell me can csrf token be passed with formData – Vinay Munjal Dec 21 '22 at 08:33
  • @VinayMunjal you can try following: https://laravel.com/docs/9.x/csrf#csrf-x-csrf-token – Dmitry K. Dec 21 '22 at 08:35
  • or you can send CSRF token in your form data: formData.append('_token', '{{ csrf_token() }}'); , or just place @csrf inside your blade template - https://laravel.com/docs/9.x/csrf#preventing-csrf-requests – Dmitry K. Dec 21 '22 at 08:37
  • Yeah its done, but now a file is saving into my database but It is not playing and showing an error that this audio can't be played can you send the controller code too. – Vinay Munjal Dec 21 '22 at 08:44
  • @VinayMunjal I need more details about this, are you trying to somehow play audio file you just stored in database? Can you share your code? Or just open new question which is much more easier – Dmitry K. Dec 21 '22 at 09:21
  • Its done now. Thank you so much for your help. – Vinay Munjal Dec 21 '22 at 10:12
  • One more ques how can i access audio located in storage folder – Vinay Munjal Dec 21 '22 at 10:14
  • @VinayMunjal hm, I have a little misunderstanding, you asked a question about how to store blob as a file in database. So, you don't have any "storage folder", your file is in database. Or did you mean you want to store file on the app server and put path to file to database? – Dmitry K. Dec 21 '22 at 10:22
  • $url = $req->file('file'); $fileName = md5(time()).".wav"; Storage::put('audio/'.$fileName.'', file_get_contents($url));___________ This is my controller code. I've successfully saved my audio to my database now I want to access this is in my blade file – Vinay Munjal Dec 21 '22 at 10:27
  • @VinayMunjal I assuming you want to get file URL, inside blade template, look at https://laravel.com/docs/9.x/filesystem#the-public-disk or https://laravel.com/docs/9.x/filesystem#file-urls – Dmitry K. Dec 21 '22 at 10:32
  • @VinayMunjal if you want to download file from server, look at https://laravel.com/docs/9.x/filesystem#downloading-files – Dmitry K. Dec 21 '22 at 10:33
  • I already tried this but nothing is working and one more thing can you share me your another platform id where i can contact you,. – Vinay Munjal Dec 21 '22 at 10:36
  • @VinayMunjal you can start discussion on SO – Dmitry K. Dec 21 '22 at 10:36
  • I don't have enough reputation to contact here, can we chat somewhere else? – Vinay Munjal Dec 21 '22 at 10:39
  • share me you telegram id. – Vinay Munjal Dec 21 '22 at 10:43