我尝试在Laravel中使用Dropzone.js上传图片,但我在上传照片后在缩略图上显示[object Object]
时出错。我无法找到错误而且我不明白原因是什么。
这是我的代码和错误的图像。为什么会这样?我该怎么办?
查看:
<div class="container col-md-8 col-12 mx-auto">
<div class="row">
<div class="col-sm-10 offset-sm-1">
<h2 class="page-heading">Upload your Images <span id="counter"></span></h2>
<form method="post" action="{{ url('/addimage') }}"
enctype="multipart/form-data" class="dropzone" id="my-dropzone">
{{ csrf_field() }}
<div class="dz-message">
<div class="col-xs-8">
<div class="message">
<p>Drop files here or Click to Upload</p>
</div>
</div>
</div>
<div class="fallback">
<input type="file" name="file" multiple>
<input type="hidden" name="id" value="{{$id}}" >
</div>
</form>
</div>
</div>
</div>
路线:
Route::group(['middleware'=>'auth'], function (){
...
Route::post('/addimage', 'FrontendController@addimage');
Route::post('/adddeleteimage', 'FrontendController@adddeleteimage');
...
});
控制器:
public function addimage(Request $request){
$file = $request->file('file');
$filename = uniqid().".".$file->clientExtension();
$file->move('img/product', $filename);
$dropzone = new Imagedb;
$dropzone->product_id = $request->id;
$dropzone->url = 'img/product'.$filename;
$dropzone->save();
}
JS:
var total_photos_counter = 0;
Dropzone.options.myDropzone = {
uploadMultiple: true,
parallelUploads: 2,
maxFilesize: 16,
acceptedFiles: "image/*",
resizeWidth: 360,
previewTemplate: document.querySelector('#preview').innerHTML,
addRemoveLinks: true,
dictRemoveFile: 'Remove file',
dictFileTooBig: 'Image is larger than 16MB',
timeout: 10000,
init: function () {
this.on("removedfile", function (file) {
$.post({
url: '/adddeleteimage',
data: {id: file.name, _token: $('[name="_token"]').val()},
dataType: 'json',
success: function (data) {
total_photos_counter--;
$("#counter").text("# " + total_photos_counter);
}
});
});
},
success: function (file, done) {
total_photos_counter++;
$("#counter").text("# " + total_photos_counter);
}
};
答案 0 :(得分:1)
首先,尝试$('meta [name =“csrf-token”]')。attr('content')作为标记
答案 1 :(得分:1)
我通过添加head标签解决了该错误
<meta name="csrf-token" content="{{ csrf_token() }}">
和在dropzone初始化配置中
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
示例:
autoProcessQueue:false,
required:true,
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg",
addRemoveLinks: true,
maxFiles:8,
parallelUploads : 100,
maxFilesize:5,
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }