遇到一个奇怪的问题,我确信这与我的脚本获取文件输入字段的值的方式有关。
我知道 Controller 功能有效,因为我已经能够通过手动提交表单而不使用 ajax 来完成它。
我还知道 ajax 在发送和接收请求方面起作用,因为我通过修改它来来回解析有效的字符串来测试它。
此外,我可以看到脚本正在抓取文件,因为当我选择文件时,它会在控制台中显示所选文件。
在我的浏览器中,我收到 500 错误,而在 Laravel 中,我只收到以下错误:
Symfony\Component\Debug\Exception\FatalThrowableError:在 C:\123\app\Http\Controllers\MyController.php:156 中的字符串上调用成员函数 getClientOriginalExtension()
我尝试更新 Controller 以使用 Request->logo,但没有成功。
查看:
<form enctype="multipart/form-data" class="form-horizontal" method="POST" action="{{ url('studio/uploadLogo') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('studioname') ? ' has-error' : '' }}">
<label for="imageInput" class="col-md-4 control-label">Logo</label>
<div class="col-md-6">
<input data-preview="#preview" name="logo" type="file" id="imageInput">
<img id="preview" src="" style="display: none"></img>
<input class="form-control" type="submit">
</div>
</div>
</form>
脚本:
$('#imageInput').change(function (e) {
e.preventDefault();
var logo = $('#imageInput').val();
console.log(logo);
$.ajax({
type: "POST",
url: '/studio/uploadLogo',
data: {logo: logo},
success: function( data ) {
console.log(data);
}
});
});
Controller :
public function uploadLogo() {
$file = Input::file('logo')->getRealPath();
$photoName = str_random(20) . '.' . Input::file('logo')->getClientOriginalExtension();
Input::get('logo')->move(public_path('avatars'), $photoName);
$response = array(
'status' => 'success',
'data' => $photoName
);
return \Response::json($response);
}
路线:
Route::post('/studio/uploadLogo', 'MyController@uploadLogo');
Route::get('/studio/uploadLogo', 'MyController@uploadLogo');
最佳答案
You just change a view js script to submit like below
$('.form-horizontal').submit(function(event){
event.preventDefault();
$.ajax({
type : 'POST',
url : "/studio/uploadLogo",
data : new FormData(this),
contentType:false,
processData:false,
})
.done(function(data,status){
//Your codes here
});
});
and
echo string response from controller like below
----------------
$file=$request->file('logo');
$uploaded_file_path='';
if($file!=null) {
$destinationPath = 'uploads';
$uploaded=$file->move($destinationPath,$file->getClientOriginalName());
$uploaded_file_path= $uploaded->getPathName();
$response = array(
'status' => 'success',
'data' => $uploaded_file_path
);
}else{
$response = array(
'status' => 'failed',
'data' => $uploaded_file_path
);
}
echo json_encode($response);
----------------
关于javascript - Laravel 无法通过 ajax 上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47904711/