前端:
<div class="col-sm-3">
<input type="file" onchange="fileuploadIdeal(this)" multiple="multiple">
</div>
<div id="image_arr_ideal"></div> // 用来展示上传之后的图片
js:
function fileupload(obj){ var data = new FormData(); for (var i = 0; i < obj.files.length; i++) { var file = obj.files[i]; // 检查文件类型 if (!file.type.match('image.*')) { alert('只支持图片类型'); return false; } // 添加文件到formData data.append('files[]', file, file.name); } if(confirm("确认上传吗?")){ $.ajax({ url : "/admin/post_upload_file", type : "POST", data : data, // 告诉jQuery不要去处理发送的数据 processData : false, // 告诉jQuery不要去设置Content-Type请求头 contentType : false, success : function(data) { if (data.code == 0) { $('#new_desc_add').val(1); $('#image_arr').html(''); var image_arr = data.data.data; for (var i = 0; i <= image_arr.length - 1; i++) { var image = '<input type="image" src="' + image_arr[i]['url'] + '" width="80px" height="100px"/> '; var imageurl = '<input type="hidden" name="descimage[]" value="' + image_arr[i]['image'] + '"/> '; $('#image_arr').append(image); $('#image_arr').append(imageurl); } }else{ alert(data.message); } }, }); } }
后端:
public function uploadFile(Request $request) { $request_all = $request->all(); $files = $request_all['imgFile']; $filesData['file'] = $files; if (!$files) { return $this->errorJson(ErrorDef::ERROR_SERVICE, '请上传文件'); } if ($request->isMethod('post')) { $image = []; foreach ($filesData as $key => $file) { // 文件是否上传成功 if (!empty($file) && $file->isValid()) { // 使用使用oss $bool = Oss::uploadObject($file); if ($bool['status'] == 1) { $image[$key]['url'] = Oss::getUrl($bool['subpath'], 'crop'); $image[$key]['image'] = $bool['subpath']; } else { return $this->errorJson(ErrorDef::ERROR_SERVICE, '文件上传失败'); } } } $filepath = $image['file']['url']; return $this->responseJson(ErrorDef::SUCCESS, ['data' => $image]); } }
public static function uploadObject(UploadedFile $file)
{
$ext = $file->getClientOriginalExtension();
return self::upload($file->getPathname(), $ext);
}
public static function upload($filePath, $ext = 'jpg', $bucket = false, $prefix = '')
{
try {
$fileMd5 = md5_file($filePath);
} catch (Exception $e) {
return ['status' => -1, 'message' => '文件未找到 或者 文件不可读'];
}
if (!$prefix) {
$prefix = config('oss.prefix');
}
$ossKey = join('/', [$prefix, substr($fileMd5, -2), substr($fileMd5, 0, 2), $fileMd5 . '.' . $ext]);
$oss = new Oss(env('USE_ALIYUN_INTERNAL', true)); // 上传文件使用内网,免流量费
if ($bucket) {
$oss->ossClient->setBucket($bucket);
}
try {
$result = $oss->ossClient->uploadFile($ossKey, $filePath);
return ['status' => 1, 'subpath' => $ossKey, 'filemd5' => $fileMd5];
} catch (Exception $e) {
return ['status' => -2, 'msg' => $e->getMessage()];
}
}
public function uploadFile($key, $file, $options = [])
{
$handle = fopen($file, 'r');
$value = $this->ossClient->putObject(array_merge([
'Bucket' => $this->bucket,
'Key' => $key,
'Content' => $handle,
'ContentLength' => filesize($file),
], $options));
fclose($handle);
return $value;
}