我试图从Mysql中的Blob列中显示一个文档(pdf或图像)。
这是我的代码上传一个pdf或图像文件。
public function store(Request $request)
{
//
Request()->validate([
'userfile' => 'required|mimes:doc,docx,pdf,jpeg,png,jpg,gif,svg|max:2048',
]);
$f = $request->file('userfile');
$att = new \App\Image;
$att->vno = $request->vno;
$att->vtype = $request->vtype;
$att->descrip = $request->docdesc;
$att->fname = $f->getClientOriginalName();
$att->imagefile = base64_encode(file_get_contents($f->getRealPath()));
$att->mime = $f->getMimeType();
$att->size = $f->getSize();
$att->save();
return response()->json(['success'=>$att->id]);
}
若要检索和显示文档,请使用以下代码。
public function show($id)
{
//
$doc = DB::table('images')->where('id',$id)->get();
$tmpdoc = $doc[0]->imagefile;
return Response::make($tmpdoc, 200, [
'Content-Type' => $doc[0]->mime,
'Content-Disposition' => 'inline; filename="'.$doc[0]->fname.'"'
]);
}
但我得到一个空白页的情况下,一个图像文件和“未能加载pdf文件”的pdf文件。
更新
使用MySQL手动上传图像和PDF文档到WorkBench,并且该图像正在正确显示。所以我认为在文件上传部分有一些问题。
上传的HTML是
<div class="col-sm-8">
<input type="text" class="form-control" id="docdesc" name="docdesc" placeholder="Enter description for document" value="">
<input type="file" id="filename" name="filename" class="form-control">
</div>
<div class="col-sm-2">
<button type="button" class="btn btn-secondary" id="addDoc">Attach</button>
</div>
和ajax代码
$('#addDoc').click(function (e) {
// Save Image to Table
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var fd = new FormData();
fd.append('userfile', $('#filename')[0].files[0]);
$.ajax({
data: fd,
url: "{{ route('images.store') }}",
cache:false,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
$('#documentForm').trigger("reset");
},
});
});
发布于 2019-12-30 18:03:08
您是否也可以尝试传递内容大小和以下标题:
return Response::make($tmpdoc, 200, [
'Content-Type' => $doc[0]->mime,
'Content-length' => strlen($tmpdoc),
'Pragma'=>'private',
'Cache-Control'=>'max-age=0',
'Content-Disposition' => 'inline; filename="'.$doc[0]->fname.'"'
]);
发布于 2019-12-31 10:32:46
删除base64_encode()解决了这个问题。
变化
$att->imagefile = base64_encode(file_get_contents($f->getRealPath()));
至
$att->imagefile = file_get_contents($f->getRealPath());
https://stackoverflow.com/questions/59534580
复制相似问题