Use Formdata and Ajax to upload pictures
Description:
Upload a single picture to the interface, return the URL and write it into the database
<input type="file" name="file" id="file" class="file">
<input type="text" name="url" id="url" class="url" value="" style="display: none;">
//设置隐藏文本框用来存储返回的url
Understanding FormData
image upload:
document.querySelector('.file').addEventListener('change', function (e) {
let files = e.target.files
//console.log(files)
// 判断是否有文件
if (!files.length) return
// 上传文件 创建FormData
// previewFile(file);
let formData = new FormData()
// upFile就是后台接收的key
formData.append('file', files[0])
// 将formdata发送到后台即可
// 使用ajax将数据发送到后台
$.ajax({
url: '接口url',
type: 'post',
//dataType: 'json',
contentType: false, //禁止设置请求类型
processData: false,
data: formData,
processData: false,
success: function (data) {
$('#url').val(data);
}
})
})
consolog.log(e) returns ==>
console.log(e.target) -->
Returns the input object:
console.log(e.target.files)-->
Returns
some attributes in a filelist that can be passed through e.target. Obtain by files[0].size
You can get the url returned by the interface through ajax, and write this url into the hidden text field. Store the url to the database through ajax.
$('#btn-save').click(function () {
$.ajax({
url: "http://localhost:8080/banner",
type: 'post',
data: {
'id': $("#id").val(),
"name": $("#name").val(),
"alt": $("#alt").val(),
"createTime": $("#createTime").val(),
'createBy': $('#createBy').val(),
"url": $('#url').val()
// "file": $("#file")
},
success: function (data) {
//alert("weqeq")
$('#banner').empty();
$('#del-x').trigger("click");
getImage();
}
})
//$('#del-x').trigger("click");
})
Click the button to save the content including the URL to the database, and close the pop-up box.