如何使用 Laravel 中的存储 class 删除和替换 .mp3 文件

How do you delete and replace a .mp3 file using the Storage class in Laravel

我正在构建一个允许用户编辑音频的工具。我的计划是这样的:

  1. 从数据库中检索音频文本并生成音频
  2. 在Laravel存储系统中存储音频文件
  3. 如果用户编辑了音频,删除旧的
  4. 将新的音频文件放在同一位置

但是,我可以轻松删除.mp3 文件。但是当我重新创建文件时,为用户播放的是旧音频文件。它有时会起作用,但只是偶尔起作用。

我的控制器代码

//this is called when the user retrieves the audio the first time and this is working fine
public function getAudioInfo(Request $request){
        ...
        $audio = audio.mp3; //just for an example, this holds an .mp3 file
        $path = "Audio/audio_type/audio_sub_type/";;
        $audio_name = $name.".mp3";
        $save_path = 'public/'.$path.$audio_name;
        Storage::put($save_path , $audio_file);

        //store needed variables in the session
        Session::put('audio_url', Storage::url($path)); //used to listen to the audio
        Session::put('audio_path', 'public/'.$path.$audio_name); //used to get the audio on html
        return back()->with('success', 'Audio retrieved');
    }

//this is where is breaks, it will delete the file but when it replaces it still plays the old
//audio for the user
    public function displayUpdatedAudio(Request $request){
        //session variables needed
        $audio_path = Session::pull('audio_path');
        ...
        $audio_file = new_audio.mp3;
        //delete old file
        Storage::delete($audio_path);
        Storage::put($audio_path, $audio_file); //this is where it seems to fail
 
        return back()->with('success', 'Audio retrieved');
    }

我的路线

    Route::get('preview_update', 'Admin\AudioController@displayUpdate')->name('preview_update');

我的html

        <form id="preview-audio" method="GET" action="{{ route('preview_update') }}">
            <div class="input-field">
                <audio controls id="audio">
                    <source src="@if(Session::has('audio_url')) <?php echo Session::get('audio_url'); ?> @endif" type="audio/mpeg">
                </audio>
            </div>
            <button type="submit" id="listen-submit-update">Get Updated Audio</button>
        </form>

mp3 文件可能已被浏览器缓存,并且再也没有请求过。为了避免浏览器缓存,您需要:

  • 向您的 mp3 文件添加一些随机内容URL
https://example.com/1.mp3?r=123
  • 或将 no-cache headers 设置为服务器响应,以便浏览器不会缓存您的文件:
->withHeaders([
    'Cache-Control' => 'no-cache, no-store, must-revalidate',
    'Pragma' => 'no-cache',
    'Expires' => '0',
]);