Javascript Laravel,ajax base64图像未正确上载
我正在使用DropzoneJS上传我的图像。因此,我要做的是获取dropzoneJS生成的base64URL,然后尝试按如下方式上载:Javascript Laravel,ajax base64图像未正确上载,javascript,jquery,laravel,base64,dropzone,Javascript,Jquery,Laravel,Base64,Dropzone,我正在使用DropzoneJS上传我的图像。因此,我要做的是获取dropzoneJS生成的base64URL,然后尝试按如下方式上载: $( document ).ready(function() { var endpoint= $("#endpoint").val(); var unit = { name: '', description: '', image: '', base64Image: '', themes: [] }
$( document ).ready(function() {
var endpoint= $("#endpoint").val();
var unit = {
name: '',
description: '',
image: '',
base64Image: '',
themes: []
}
$("#create-unit-btn").on("click", function() {
unit.name = $("#create-name").val();
unit.description = $("#create-description").val();
unit.base64Image = $('#imageDropzone')[0].dropzone.files[0].dataURL;
var data = {
'_token': $('meta[name=csrf-token]').attr('content'),
'unit': unit
}
console.log(data);
$.ajax({
type: "POST",
url: endpoint,
data: data,
success: function(result){
console.log(result);
}
});
});
function validate() {
}
});
然后使用以下代码上传图像:
public function create( Request $request ) {
$data = [];
$code = 200;
try {
$unit = new Unit();
$unit->name = request()->input('unit.name');
$unit->description = request()->input('unit.description');
$url = ImageHandler::StoreBase64ToFile($request->input('unit.base64Image'));
$unit->image = $url;
$unit->save();
$data['unit'] = $unit;
} catch ( \Illuminate\Database\QueryException $e ) {
// There was an error
$code = Response::HTTP_UNPROCESSABLE_ENTITY;
$data = [];
$data['error'] = ErrorResponse::create($code, $e->getMessage());
} catch( ModelNotFoundException $e ) {
return response()->json(['error' => 'invalid operation'], 406);
}
return response()->json($data, $code);
}
ImageHandler类执行以下操作:
<?php
namespace App\Libraries;
use Storage;
class ImageHandler {
/**
* Store a base64 image into the file system this data has to be
* sended without any header info like:
* data:image/png;base64
* So the info will look something like iVBORw0....hEUgAAAcQ==
* @param string $base64Data information
* @param string $filename the filename if not defined then it generates
* a random name
* @param string $disk disk location, check Storage documentation of
* laravel, by default is stored on the public folder
* so you'll have to run
* php artisan storage:link
* to make the symbolink links
* @return string url location of the file
*/
public static function StoreBase64ToFile($base64Data,
$filename = null,
$disk = 'public')
{
if (strlen($base64Data) < 10) {
return null;
}
$image = base64_decode($base64Data);
if ($filename == null) {
$filename = str_random(16);
$filename .= '_'.time();
$filename .= '.png';
}
$path = 'images/'.$filename;
$result = Storage::disk($disk)->put($path, $image, 'public');
if ($result) {
$url = Storage::disk($disk)->url($path);
return $url;
}
return null;
}
}
当我存储图像时,是格式错误。为了上传文件没有任何问题,我必须在发送请求之前执行以下操作:unit.base64Image=unit.base64Image.replace(“数据:image/png;base64,”,”)代码>