laravel-5 - 在 Laravel Controller 中保存 blob 图像

标签 laravel-5 vuejs2 image-uploading

在我的 Laravel 5/vuejs 2.6 中,我上传了一个带有 vue-upload-component 的图像并发送了一个请求的图像 blob
我尝试使用 Controller 代码保存它,例如:

    if ( !empty($requestData['avatar_filename']) and !empty($requestData['avatar_blob']) ) {
        $dest_image = 'public/' . Customer::getUserAvatarPath($newCustomer->id, $requestData['avatar_filename']);

        $requestData['avatar_blob']= str_replace('blob:','',$requestData['avatar_blob']);
        Storage::disk('local')->put($dest_image, file_get_contents($requestData['avatar_blob']));
        ImageOptimizer::optimize( storage_path().'/app/'.$dest_image, null );
    } // if ( !empty($page_content_image) ) {

结果,我上传了一张图片,但它不可读。
源文件有 5 Kib,结果文件有 5.8 Kib,在浏览器的控制台中,我看到 blob 路径为
avatar_blob: "blob:http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af"

我是否必须转换我的 blob 以正确保存它?

已修改 :
更详细一点:
在 vue 文件中,我使用 axios 发送请求:
               let customerRegisterArray =
                    {
                        username: this.previewCustomerRegister.username,
                        email: this.previewCustomerRegister.email,
                        first_name: this.previewCustomerRegister.first_name,
                        last_name: this.previewCustomerRegister.last_name,
                        account_type: this.previewCustomerRegister.account_type,
                        phone: this.previewCustomerRegister.phone,
                        website: this.previewCustomerRegister.website,
                        notes: this.previewCustomerRegister.notes,
                        avatar_filename: this.previewCustomerRegister.avatarFile.name,
                        avatar_blob: this.previewCustomerRegister.avatarFile.blob,
                    };
                console.log("customerRegisterArray::")
                console.log(customerRegisterArray)

                axios({
                    method: ('post'),
                    url: window.API_VERSION_LINK + '/customer_register_store',
                    data: customerRegisterArray,
                }).then((response) => {
                    this.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::"+var_dump() )
                }).catch((error) => {
                });

并且 this.previewCustomerRegister.avatarFile.blob 具有值:“blob:http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af
哪里http://local-hostels2.com是我主持...
我将此值设置为预览图像定义为:
            <img
                class="img-preview-wrapper"
                :src="previewCustomerRegister.avatarFile.blob"
                alt="Your avatar"
                v-show="previewCustomerRegister.avatarFile.blob"
                width="256"
                height="auto"
                id="preview_avatar_file"
            >

当 previewCustomerRegister.avatarFile.blob 被分配给上传的文件时,我在预览图像中看到它。
我在第一个主题中使用保存功能显示控制,但是当我尝试用 kate 打开我生成的文件时,我发现它
有我的容器文件 resources/views/index.blade.php 的内容...

我做错了什么,哪种方法是有效的?

修改后的块 #2:
我在请求中添加了“内容类型”
axios({
  method: ('post'),
  url: window.API_VERSION_LINK + '/customer_register_store',
  data: customerRegisterArray,
  headers: {
    'Content-Type': 'multipart/form-data'
  }

但是有了它,我的控件中出现了验证错误,因为我使用请求定义了控制操作:
public function store(CustomerRegisterRequest $request)
{

并在 app/Http/Requests/CustomerRegisterRequest.php 中:
<?php

namespace App\Http\Requests;

use App\Http\Traits\funcsTrait;
use Illuminate\Foundation\Http\FormRequest;
use App\Customer;
class CustomerRegisterRequest extends FormRequest
{
    use funcsTrait;

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $request= Request();
        $requestData= $request->all();

        $this->debToFile(print_r( $requestData,true),'  getCustomerValidationRulesArray $requestData::');
        /* My debugging method to write data to text file 
        and with Content-Type defined above I see that $requestData is always empty
        and I got validations errors
         */

        // Validations rules 
        $customerValidationRulesArray= Customer::getCustomerValidationRulesArray( $request->get('id'), ['status'] );
        return $customerValidationRulesArray;
    }
}

在 routes/api.php 中定义:
Route::post('customer_register_store', 'CustomerRegisterController@store');

在浏览器的控制台中,我看到:https://imgur.com/a/0vsPIsa , https://imgur.com/a/wJEbBnP

我想 axios 头文件有问题?没有“内容类型”定义我的验证规则工作正常......

修改后的第 3 块

我设法使用如下方法获取 blob:
            var self = this;

            fetch(this.previewCustomerRegister.avatarFile.blob) .then(function(response) {
                console.log("fetch response::")
                console.log( response )

                if (response.ok) {
                    return response.blob().then(function(myBlob) {
                        var objectURL = URL.createObjectURL(myBlob);
                        // myImage.src = objectURL;
                        console.log("objectURL::")
                        console.log( objectURL )

                        console.log("self::")
                        console.log( self )



                        let customerRegisterArray =
                            {
                                username: self.previewCustomerRegister.username,
                                email: self.previewCustomerRegister.email,
                                first_name: self.previewCustomerRegister.first_name,
                                last_name: self.previewCustomerRegister.last_name,
                                account_type: self.previewCustomerRegister.account_type,
                                phone: self.previewCustomerRegister.phone,
                                website: self.previewCustomerRegister.website,
                                notes: self.previewCustomerRegister.notes,
                                avatar_filename: self.previewCustomerRegister.avatarFile.name,
                                avatar: objectURL,
                            };

                        console.log("customerRegisterArray::")
                        console.log(customerRegisterArray)

                        axios({
                            method: 'POST',
                            url: window.API_VERSION_LINK + '/customer_register_store',
                            data: customerRegisterArray,
                            // headers: {
                            //     'Content-Type': 'multipart/form-data'  // multipart/form-data - as we need to upload with image
                            // }
                        }).then((response) => {
                            self.is_page_updating = false
                            self.message = ''
                            self.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
                            alert( "SAVED!!::")
                        }).catch((error) => {







  self.$setLaravelValidationErrorsFromResponse(error.response.data);
                            self.is_page_updating = false
                            self.showRunTimeError(error, this);
                            self.showPopupMessage("Customer Register", 'Error adding customer ! Check Details fields !', 'warn');
                            // window.grecaptcha.reset()
                            self.is_recaptcha_verified = false;
                            self.$refs.customer_register_wizard.changeTab(3,0)
                        });


                    });
                } else {
                    return response.json().then(function(jsonError) {
                        // ...
                    });
                }
            }).catch(function(error) {
                console.log('There has been a problem with your fetch operation: ', error.message);
            });

在 objectURL 和 self 我看到正确的值:https://imgur.com/a/4YvhbFz

1) 但是在 laravel 的控件中检查服务器上的数据,我看到与我开始尝试上传图像时的值相同:

[avatar_filename] => patlongred.jpg
[头像] => blob:http://local-hostels2.com/d9bf4b66-42b9-4990-9325-a72dc8c3a392

必须以其他方式使用获取的 bnlob 进行操作?

2)如果我设置:
  headers: {
    'Content-Type': 'multipart/form-data'
  }

我收到验证错误,表明我的数据请求不正确...

?

最佳答案

您使用的请求类型为 application/json因此您将无法以这种方式保存图像,对于文件上传,请求类型应为 multipart/form-data在这种情况下,您需要将请求发送为

let customerRegisterArray = new FormData();
customerRegisterArray.put('username', this.previewCustomerRegister.username);
customerRegisterArray.put('email', this.previewCustomerRegister.email);
....
customerRegisterArray.put('avatar', this.previewCustomerRegister.avatarFile);

console.log("customerRegisterArray::")
console.log(customerRegisterArray)

axios({
  method: ('post'),
  url: window.API_VERSION_LINK + '/customer_register_store',
  data: customerRegisterArray,
  headers: {
    'Content-Type': 'multipart/form-data'
  }
}).then((response) => {
     this.showPopupMessage("Customer Register", 'Customer added successfully !Check entered email for activation link !', 'success');
     alert( "SAVED!!::"+var_dump() )
}).catch((error) => {});

关于laravel-5 - 在 Laravel Controller 中保存 blob 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480146/

相关文章:

html - 在 React 中使用表单数据上传图像

java - 将照片上传到 ParseUser 对象时,它会被保存到我添加的上一个用户

javascript - 仅在首次加载时使用 nuxt.js 设置数据

php - 使用 mysql codeigniter 图像更新 null

php - Laravel 邮件附件超时

php - Artisan 控制台命令在 5.1 中不起作用

php - Laravel 5,单击表单提交按钮时不显示任何内容

php - 无法在php laravel框架中创建 Controller 和模型

javascript - Vuejs 2.3 - 同步和元素 Ui 对话框

Sass 嵌套样式带来忽略/无效