前端用element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="/vue.js"></script>
<script src="/axios-0.18.0.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="zy1">
你的姓名:<input v-model="name" /><br>
<input type="file" v-model="tp" />
[{{tp}}]
<!-- <br>
<input type="button" value="上传" @click="uploading" /> -->
<br>
<br>
<el-upload class="upload-demo" action="http://127.0.0.1:8080/up/loading" :on-preview="handlePreview"
:on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
<script>
new Vue({
el: "#zy1"
, data: {
name: ''
, tp: ''
, fileList: []
},
methods: {
uploading: function () {
var formData = new FormData();
formData.append('File', this.tp);
if (this.tp == '') {
alert("不能上传空文件")
return fales;
}
axios.post("http://127.0.0.1:8080/up/loading", {
params: {
name: this.name,
file: formData
}
}, { headers: { 'Content-Type': 'multipart/form-data' } }).then((ret) => {
console.log(ret.data)
})
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
}
}
})
</script>
</body>
</html>
后端boot
package com.xxx.pro; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; @CrossOrigin(origins="*") @Controller @RequestMapping("/up") public class io { @RequestMapping("/loading") @ResponseBody public String uploading(@RequestParam(name = "file",required=false) MultipartFile file ) { if (file.isEmpty()) { return "文件为空"; } // 获取文件名 String fileName = file.getOriginalFilename(); System.out.println("上传的文件名为:" + fileName); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); System.out.println("上传的后缀名为:" + suffixName); // 文件上传后的路径 String filePath = "D://"; File dest = new File(filePath + fileName); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上传成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上传失败"; } }