vue+springboot+element+vue-resource實現文件上傳
vue頁面設置
<el-upload
class="upload-demo"
action=""
:before-upload="beforeUpload" //上傳前操作
:before-remove="beforeRemove" //移除錢操作
:multiple="false" //禁止多選
:http-request="myUpload" //文件上傳,重寫文件上傳方法,action的路徑不會起作用
accept=".jar" //限制文件選擇類型
:drag="false"
:data="param" //參數
:file-list="fileList">//文件顯示列表
<el-button size="small" type="primary">點擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jar文件,且不超過500kb</div><!-- :headers="head"-->
</el-upload><!--:on-preview="handlePreview"-->
/*文件上傳前,判斷文件名是否存在,等其他處理*/
beforeUpload(file){
console.log("文件名",file.name,this.fileList)
for (let i = 0; i <this.fileList.length ; i++) {
if (this.fileList[i].name==file.name) {
this.$message.info("文件已存在");
return false;
}
}
this.file=file;
return true;
},
/*文件移除前,提示是否刪除*/
beforeRemove(file,fileList){//delJar
this.$confirm('此操作將永久刪除該文件, 是否繼續?', '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http.get('/aaaa/task/del?taskId='+this.taskId+'&name='+file.name).then(function(res) {
......
});
}).catch(() => {
this.getJarList();
return false;
});
},
/*文件上傳,重寫文件上傳方法,action的路徑不會起作用*/
myUpload(file){
let fd = new FormData();
fd.append('file',this.file);//傳文件
fd.append('taskId',this.taskId);//傳其他參數
// fd.append('filename',file.name);//傳其他參數
this.$http.post('/aaaa/task/add',fd).then(function(res) {
....
});
},
fileList一個對象的內容
name:"xxxx.jar"
status:"success"
uid:123456456
參數
this.param={
taskId:this.taskId
}
springboot設置
1.請求的注解:produces = "multipart/form-data;charset=utf-8", method = RequestMethod.POS
@RequestMapping(value = "/add", produces = "multipart/form-data;charset=utf-8", method = RequestMethod.POST)
public String addJar(int taskId, HttpServletRequest request) throws IOException, ServletException {
....
//獲取文件
Part part = request.getPart("file");// input的name值
String dis = part.getHeader("Content-Disposition");
// 獲取文件名--sdsf.jar
String fna = dis.substring(dis.indexOf("filename=") + 10, dis.length() - 1);
String fname = fna.substring(fna.lastIndexOf("\\\\") + 1, fna.length());// 有的瀏覽器獲取的是路徑+文件名
// 若是文件名為空,說明此時沒有選擇文件,返回,文件上傳失敗,選擇文件
if (fname.length() < 1) {
//此時沒有選擇文件
}
....
}
附件列表