上传端
HTTP协议中有对文件传输的支持,另一个后端服务器发送请求(前端同理,符合HTTP协议即可),主要需要设置两个属性:
①Content-Disposition,设置为“form-data;name=文件名称(可自定义);filename=文件全程包括后缀名”
②Content-Type,设置为application/octet-stream(一般用于文件上传下载,代表传输的数据是二进制流)
Ps:提供一段简略的前端vue代码以便调试,样式可自行调整
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
<title>Upload Demo</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" />
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<style>
body,
html {
font-family: "Fixedsys";
font-size: 0.7vw;
}
body {
overflow-y: hidden;
/* overflow-x: scroll; */
}
#app {
width: 100%;
height: 100%
}
html::-webkit-scrollbar {
display: none;
}
::-webkit-scrollbar {
width: 10px;
height: 10px;
cursor: pointer;
}
::-webkit-scrollbar-thumb {
background-color: #a1a3a9;
border-radius: 5px;
cursor: pointer;
}
</style>
<body>
<div id="app">
<el-upload
class="upload-demo"
action="http://localhost:8080/upload/demo"
:on-change="handleChange"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</div>
<body>
<script>
var vm = new Vue({
el: '#app',
data: {
fileList: []
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList.slice(0,1);
}
}
});
</script>
</html>
接收端
直接上代码,需要注意的地方会标注在代码注释上
/*实际项目中处理逻辑写在Service层*/
@RestController
@RequestMapping("/upload")
public class UploadController {
@PostMapping("/demo")
public void uploadMethod(HttpServletRequest request, HttpServletResponse response) {
//跨域请求,*代表允许全部类型
response.setHeader("Access-Control-Allow-Origin", "*");
//允许请求方式
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//用来指定本次预检请求的有效期,单位为秒,在此期间不用发出另一条预检请求
response.setHeader("Access-Control-Max-Age", "3600");
//请求包含的字段内容,如有多个可用哪个逗号分隔如下
response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization, x-ui-request,lang");
//访问控制允许凭据,true为允许
response.setHeader("Access-Control-Allow-Credentials", "true");
// 浏览器是会先发一次options请求,如果请求通过,则继续发送正式的post请求
try {
//设置编码
request.setCharacterEncoding("UTF-8");
/**request.getPart用来获取文件内容与文件
信息,getParts是getPart的批量获取方法*/
Collection<Part> list = request.getParts();
list.forEach(part -> {
if (part.getName().equals("file")) {
//保存文件路径,可自行定义,注意在windows系统下文件夹分隔符为\\
//getSubmittedFileName用来获取文件的名称(包括后缀名)
String saveFileName = "d:\\" + part.getSubmittedFileName();
try {
//最关键的一步,将上传的文件内容写入上面路径对应的文件中
part.write(saveFileName);
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
}
}
});
} catch (Exception e) {
System.out.println("上传文件失败");
}
}
}