我将图片上传到我的基地和存储(这可行),但是当我尝试下载图片时,我会收到错误的非法字符。
$(document).on('submit','#formToAjax',function(event){
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
cache: false,
processData: false,
contentType: false,
success: function (data, status){
console.log(data);
},
error: function (xhr, desc, err){
console.log(xhr);
console.log(desc);
console.log(err);
}
});
})
和我的控制器
public function UploadImage() {
$file = Request::file('filefield');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new Upload();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
$file = Storage::disk('local')->get($entry->filename);
return (new Response($file, 200))->header('Content-Type', $entry->mime);
}
当我尝试从控制器返回图像时,这是错误的:
如果我不使用ajax,那么图像正常加载。
答案 0 :(得分:0)
我找到了这个结果。在控制器中我返回的不是图像而是filname上传图像。
public function UploadImage() {
$file = Request::file('filefield');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new Upload();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
return $entry->filename;
}
在我的ajax中,我打电话给我的路线下载图片
$(document).on('submit','#formToAjax',function(event){
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: new FormData(this),
cache: false,
processData: false,
contentType: false,
success: function (data, status){
$(".test").html('<img src="/admin/upload/get/'+data+'" class="img-responsive" />');
}
});
})
这是下载图片
public function UploadGet($filename){
$entry = Upload::where('filename', '=', $filename)->firstOrFail();
if($exists = Storage::disk('local')->exists($entry->filename)){
$file = Storage::disk('local')->get($entry->filename);
}else{
$file = 'dupa';
}
return (new Response($file, 200))->header('Content-Type', $entry->mime);
}
也许它会帮助某人:)