通过jQuery Ajax使用FormData对象上传文件

时间:2022-02-01 16:23:53

废话不说直接上代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
<style>
.fileImg {
position: relative;
box-sizing: border-box;
width: 80px;
height: 80px;
margin-top: 20px;
}

.fileImg img {
width: 100%;
height: 100%;
}

.delImg {
position: absolute;
right: -10px;
top: -10px;
width: 20px;
height: 20px;
background-color: #D9534F;
color: #FFFFFF;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
text-align: center;
font-size: 22px;
font-weight: bold;
line-height: 1;
cursor: pointer;
}
</style>
<script>
$(function() {
$("#file").on("change", function() {
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
//一般后台会返回个图片路径,然后将路径放到页面显示就可以了

}).fail(function(res) {

});

})
})
</script>
</head>

<body>

<div class="fileImg">
<img src="/img/2.png" />
<div class="delImg">×</div>
</div>
<div id="uploadForm">
<input id="file" type="file" />
</div>
</body>

</html>

  

参考链接    https://www.jianshu.com/p/46e6e03a0d53