我正在将图片保存到公共文件夹,现在我想将其显示在已定义的 <div class="logo">
中,如何实现?
控制器:
public function testing(Request $request) {
if($request->hasFile('img'));
{
$image = Input::file('img');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('images/' . $filename);
Image::make($image->getRealPath())->resize(200, 200)->save($path);
$file = $request->file('img');
return response()->file($file);
}
}
JS:
function submitImage(){
var fd = new FormData($("#upload_form")[0]);
fd.append( 'img', $('#img') );
$.ajax({
url:'template',
data: fd,
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
});
}
刀片:
<form id="upload_form" action="{{ action('BuilderController@testing') }}" enctype="multipart/form-data" role="form" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input name="img" id="img" class="form-control filestyle margin images" data-input="false" type="file" data-buttonText="Upload Logo" data-size="sm" data-badge="false" onchange="submitImage();" />
</form>
<div class="logo">
<img class="images" id="image" src="#" alt="Your Logo"/>
</div>
所以我想将 src="#"
更改为保存图片的路径,例如 "C://xampp/htdocs/laravel/public/image/1.jpg"
答案 0 :(得分:2)
将控制器方法中的return
更改为:
return ['url' => url('images/' . $filename)];
然后在success
电话中添加ajax
方法:
$.ajax({
url:'template',
data: fd,
dataType: 'json',
async: false,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
$("#image").attr("src", data.url)
}
});
希望这有帮助!
答案 1 :(得分:0)
将控制器代码更改为
public function testing(Request $request) {
if($request->hasFile('img'));
{
$image = Input::file('img');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('images/' . $filename);
Image::make($image->getRealPath())->resize(200, 200)->save($path);
$file = $request->file('img');
$response = [];
$response['name'] = $path;
return json_encode($response);
}
}
并在你的JS中添加一个成功代码,它将改变图像的URL
$.ajax({
url:'template',
data: fd,
dataType:'json',
async:false,
type:'post',
success: function (data) {
var img_loc = JSON.parse(data).name;
$("#image").attr('src', img_loc);
},
processData: false,
contentType: false,
});
}