[英]upload image in Laravel before submitting form using ajax
I have written some watermark code in Laravel and it is working fine. 我已经在Laravel中写了一些水印代码,并且工作正常。 But now I want to show the preview before submitting the file.
但是现在我想在提交文件之前显示预览。 But I am getting error "POST 419 (unknown status)"
但我收到错误消息“ POST 419(未知状态)”
My view source code is 我的查看源代码是
<form class="form-horizontal" method="POST" action="{{ route('announcement.store') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<label for="description">Description</label>
<textarea id="my-editor" class="textarea" name="description" ></textarea>
<label for="image">Featured Image</label>
<input type="file" id="image" name="image">
<button type="submit" class="btn btn-success">Submit</button>
</form>
Javascript code JavaScript代码
$(document).ready(function() {
$("#image").change(function(e) {
var image = $('#image').val();
$.ajax({
type: 'POST',
url:'{{url('/my-admin/imageupload')}}',
data: {image:image},
success: function( msg ) {
alert(msg);
},
error: function( data ) {
alert(data);
}
});
});
In this code, when I change the image I get error. 在这段代码中,当我更改图像时出现错误。 I have done some watermark on image and save that image in folder.
我在图像上做了一些水印并将该图像保存在文件夹中。 Now, I need to show that image on preview before submitting the form.
现在,我需要在提交表单之前在预览中显示该图像。
Image will not be sent with this "var image = $('#image').val();" 图片将不会通过“ var image = $('#image')。val();”发送。 piece of code while using ajax request as you need to use data = new FormData();
使用ajax请求时的一段代码,因为您需要使用data = new FormData(); for image.
用于图像。
You missed _token as data to submit on ajax, so change the data to 您错过了_token作为要在ajax上提交的数据,因此将数据更改为
data: {
"_token": "{{ csrf_token() }}",
"image":image
},
I have successfully uploaded the image by this code. 我已经通过此代码成功上传了图片。
$("#image").change(function(e) {
var data = new FormData();
data.append('image', $('input[type=file]')[0].files[0]);
data.append('_token', "{{ csrf_token() }}");
$.ajax({
url:'{{url('/my-admin/imageupload')}}',
type: 'POST',
data : data,
enctype : 'multipart/form-data',
contentType: false,
processData: false,
success: function( data ) {
var baseUrl = "{{asset('')}}";
var imageUrl = baseUrl + data.msg;
$('#changeimage').html('<img src="'+ imageUrl +'" height="120px" width="150px">');
},
error: function() {
alert('unable to insert watermark on image');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.