预备知识
文件上传使用的是POST接口,发送的Content-Type 为multipart/form-data
上传
前端上传的html实现
<form action="/web/upload/image" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/png,image.jpg" />
<input type="submit" value="添加"/>
</form>
上传js实现
js上传主要使用XMLHttpRequest和FormData对象以及表示上传进度的ProgressEvent对象。
<div class="container">
<form id="fileUpload" action="/web/upload/image" method="post" enctype="multipart/form-data">
<input id="uploadInput" type="file" name="file" accept="image/png,image.jpg" />
<input type="submit" value="添加"/>
</form>
</div>
<script type="text/javascript">
var form = document.getElementById('fileUpload');
form.onsubmit = function(event){
event.preventDefault();
var uploadInput = document.getElementById("uploadInput");
//files js FileList对象
var file = uploadInput.files[0]
/**
* file js File对象,包含以下信息
* lastModified:1480827962683
* lastModifiedDate:Sun Dec 04 2016 13:06:02 GMT+0800 (中国标准时间)
* name:"IMG_2265.PNG"
* size:74278
* type:"image/png"
* webkitRelativePath:""
*/
console.log(file);
var data = {name:uploadInput.name,file:file};
uploadFile(event.srcElement.action,data,complete,error,progress,start,end);
}
function complete(progressEvent) {
console.log('complete : ', progressEvent);
}
function error(progressEvent) {
console.log('error : ' , progressEvent);
}
function progress(progressEvent) {
console.log('progress : ' , progressEvent);
}
function start(progressEvent) {
console.log('start : ', progressEvent);
}
function end(progressEvent) {
console.log('end : ' , progressEvent);
}
/**
*
* @param url POST url地址
* @param file 上传的文件对象
* @param complete 上传完成回调
* @param error 上传错误回调
* @param progress 上传进度回调
* @param start 开始上传回调
* @param end 上传结束
*/
function uploadFile(url,data,complete,error,progress,start,end) {
var request = new XMLHttpRequest();
var formData = new FormData();
formData.append(data.name,data.file);
//true 表示异步请求
request.open("post",url,true);
request.onload = complete;
request.onerror = error;
request.upload.onprogress = progress;
request.upload.onloadstart = start;
request.upload.onloadend = end;
request.send(formData);
}