<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="file" id="fileUpload">
<button id="submit">点击上传文件</button>
<script src="javascripts/jquery-3.2.1.min.js"></script>//此处需自己引入jquery文件
<script>
//方法一:原生ajax上传文件
document.getElementById(‘submit‘).onclick = function(){
var file = document.getElementById(‘fileUpload‘).files[0];
var formData = new FormData();
formData.append(‘name‘,‘libin‘);
formData.append(‘userFile‘,file);
var oFileBody = ‘<a id="a"><b id="b">hey!</b></a>‘; // Blob对象包含的文件内容
var oBlob = new Blob([oFileBody], { type: "text/xml"});
var oReq = new XMLHttpRequest();
oReq.open("POST", "http://localhost:3000/formUpload");
// 文件上传完毕的回调
oReq.upload.onloadend = function(e) {
console.log(‘接收完成‘+e.loaded+‘/‘+e.total);
}
oReq.send(formData);
//方法二:通过jquery的ajax方法上传文件
document.getElementById(‘submit‘).onclick = function(){
var file = document.getElementById(‘fileUpload‘).files[0];
var formData = new FormData();
formData.append(‘name‘,‘libin‘);
formData.append(‘userFile‘,file);
$.ajax({
url: ‘http://localhost:3000/formUpload‘,
data: formData,
contentType: false,
processData: false,
type: ‘POST‘,
success: function (result) {
console.log(result);
},
error: function (err) {
console.error(err);
}
});
}
</script>
</body>
</html>