我正在使用十月創建一個與我的移動應用程序通信的API。在這個過程中,我發送了一個格式爲base64的圖像,直到這個部分沒有問題,因爲我將這個base64圖像轉換爲JPG格式,問題在於將這個JPG圖像保存在第二部分中十月的標準過程,即保存System_Files文件。十月CMS - 帶上傳文件的API
做這種上傳的最佳方法是什麼?
我正在使用十月創建一個與我的移動應用程序通信的API。在這個過程中,我發送了一個格式爲base64的圖像,直到這個部分沒有問題,因爲我將這個base64圖像轉換爲JPG格式,問題在於將這個JPG圖像保存在第二部分中十月的標準過程,即保存System_Files文件。十月CMS - 帶上傳文件的API
做這種上傳的最佳方法是什麼?
我假設你用某種關係來保存該文件。
for ex: profile picture etc.. (so in this case you try to attach that file to user)
所以以此爲例。
裏面user model
你可以從移動應用程序收到請求時與base64
編碼的文件
you mentioned you are successfully converting to
jpeg
but for example I just added rough code for that as well.
// we assume you post `base64` string in `img`
$img = post('img');
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$imageData = base64_decode($img);
// we got raw data of file now we can convert this row data to file in dist and add that to `File` model
$file = (new \System\Models\File)->fromData($imageData, 'your_preferred_name.jpeg');
// attach that $file to Model
$yourModel->avatar = $file;
$yourModel->save();
OR if you don't save that file with relation you can now point that file with
$file->id
and find it next time or save it for later use.
// next time
// $file->id
$yourFile = \System\Models\File::find($file->id);
現在您的文件
public $attachOne = [
'avatar' => 'System\Models\File'
];
現在定義你們的關係保存下一次你需要該文件,你可以直接使用該文件
$imageData = $yourModel->avatar->getContents();
$imageBase64Data = base64_encode($imageData);
// $imageBase64Data <- send to mobile if needed.
如果有什麼不清楚請評論。
非常感謝支持! – Crazy
我有這個錯誤:試圖獲取非對象的屬性,我相信它是在這個部分://將該文件附加到Model $ yourModel-> avatar = $ file; – Crazy
似乎沒有創建文件對象,可以使用'$ imageData'調試它,如果它存在 –