一、前端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.2/index.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.4/qs.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.4.3/vue-router.js"></script>
<link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.2/theme-chalk/index.css" rel="stylesheet">
<script src="../js/base.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app" style="width: 50%;text-align: center;">
<el-upload style="padding-top: 10%;" class="upload-demo" ref="upload" action="#" :file-list="fileList" :on-change="handleChange"
:auto-upload="false" :headers="headers" multiple>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<el-button style="margin-left: 10px;" size="small" type="info" @click="download">下载到本地</el-button>
<div slot="tip" class="el-upload__tip">【格式任意】</div>
</el-upload>
</div>
</body>
<script type="text/javascript">
var Main = {
data() {
return {
fileList: [],
headers: {
'Content-Type': 'multipart/form-data'
}
};
},
methods: {
download() {
location.href = "http://localhost:8080/transfer/download";
},
submitUpload() {
var param = new FormData();
this.fileList.forEach(
(value, index) => {
param.append("file", value.raw);
});
axios.post("/transfer/upload", param).then(responce => {
this.$message({
message: responce.data,
duration: 1000
});
});
},
handleChange(files, fileLists) {
this.fileList = fileLists;
}
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
</script>
</html>
- 【上传】本例使用了elementUI的el-button标签,将前端文件转换成FormData的格式,通过axios的post请求,发送到后端
- 【下载】
location.href = "http://localhost:8080/transfer/download";
通过location.href的方式,向后端发送请求
二、后端
package com.han.sale.handler;
import com.han.common.entity.ResponseBean;
import com.han.common.entity.StatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;
@Controller
@RequestMapping("transfer")
public class TransferHandler {
private static String FILE_NAME = null;
private static String UPLOAD_DIR = null;
@PostMapping("upload")
public ResponseEntity upload(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
String fileName = file.getOriginalFilename();
String realPath = request.getServletContext().getRealPath("uploadDir/");
File filePath = new File(realPath);
if (!filePath.exists()) {
filePath.mkdir();
}
String absPath = realPath + fileName;
TransferHandler.FILE_NAME = absPath;
TransferHandler.UPLOAD_DIR = realPath;
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(absPath));
outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();
return ResponseEntity.ok(new ResponseBean(StatusCode.OPERATE_SUCCESS, "上传成功!"));
}
@GetMapping("download")
public HttpServletResponse download(HttpServletResponse response) throws Exception {
File file = new File(TransferHandler.FILE_NAME);
String name = file.getName();
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
inputStream.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(new String(name.getBytes()), "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream");
BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
File fileDir = new File(TransferHandler.UPLOAD_DIR);
File[] files = fileDir.listFiles();
Objects.requireNonNull(files);
for (File f : files) {
f.delete();
}
return response;
}
}
- 本文实现了简单的文件上传和下载,未对上传的文件做数据处理,后端代码注释详见代码块内容;