参考博客:https://www.cnblogs.com/lenve/p/10782774.html
vue代码
<template>
<input type="file" ref="myfile">
<el-button @click="importData" type="success" size="mini">导入数据</el-button>
</template>
<script>
import axios from 'axios';
//统一设置axios请求上的Credentials
axios.defaults.withCredentials = true;
export default {
components:{
axios
},
methods:{
importData() {
let myfile = this.$refs.myfile;
let files = myfile.files;
let file = files[0];
var formData = new FormData();
formData.append("file", file);
axios({
method: 'post',
url: 'http://localhost:10010/yp/upload',//跳转路径
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
}
});
},
}
}
</script>
java代码
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
public class AddFileMapper {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
DecimalFormat df = new DecimalFormat("######0.00");
@RequestMapping("/yp/upload")
public String importData(MultipartFile file, HttpServletRequest req) throws IOException {
try{
String format = sdf.format(new Date());
//路径方式:1、绝对路径
String realPath = "F:/S3Project/vue_project/src/assets/upload"+format;
//路径方式:2、相对路径
//String realPath = req.getServletContext().getRealPath("/upload") + format;
System.out.println("存放路径:"+realPath);
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
file.transferTo(new File(folder,newName));
String url = "http://localhost:3000/src/assets/upload" + format + newName;
//String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/upload" + format + newName;
System.out.println("前端访问路径:"+url);
//文件名称
String fileName="/upload" + format + newName;
//文件大小
String fileSize = df.format((file.getSize()/1024))+"kb";
System.out.println("文件名称:"+fileName+"---文件大小"+fileSize);
}catch (Exception e){
return "上传失败";
}
return "上传成功";
}
}
配置文件
上传的文件大小默认是1MB,我们可以在application.yaml里设置上传的文件大小限制
spring:
servlet:
multipart:
max-file-size: 10MB