一、效果图
前端页面:
在java这边后端的target文件就可以接收到前端发送的文件,文件可以打开
接下来看具体代码是怎么实现的!
二、代码部分
Vue代码
<template> <el-upload ref="upload" class="upload-demo" action="http://localhost:9090/api/upload" <!--这个为后端响应的路径-->:on-success="handleSuccess" :before-upload="beforeUpload" :file-list="fileList" :auto-upload="false" :on-change="handleChange" > <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件,且不超过500kb</div> </el-upload>
</template> <script>
export default { // ... 其他代码保持不变 data() { return { fileList: [] }; }, methods: { handleSuccess(response, file, fileList) { console.log('文件上传成功:', response); }, beforeUpload(file) { // 限制格式为excel// 如果不想限制可以将这行代码去掉,以及后面的一些关于excel的判断const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'; // 限制文件大小const isLt2M = file.size / 1024 / 1024 < 0.5; if (!isExcel) { this.$message.error('上传文件只能是 xls/xlsx 格式!'); } if (!isLt2M) { this.$message.error('上传文件大小不能超过 500KB!'); } return isExcel && isLt2M; }, submitUpload() { // 这边的$refs.upload要与上面第三行的ref一致this.$refs.upload.submit(); }, handleRemove(file, fileList) { console.log('移除文件', file, fileList); }, handleChange(file, fileList) { this.fileList = fileList; } }
};
</script>
后端代码
(1)首先导入依赖
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.8.0</version></dependency>
(2)controller层(也可以在servlet写)
@RequestMapping(value = "/upload")public void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{// 检查请求是否为多部分请求if (!ServletFileUpload.isMultipartContent(request)) {throw new ServletException("Content type is not multipart/form-data");}// 配置上传参数DiskFileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);try {// 解析请求的内容提取文件数据List<FileItem> formItems = upload.parseRequest(request);if (formItems != null && formItems.size() > 0) {// 迭代表单数据for (FileItem item : formItems) {// 处理不在表单中的字段if (!item.isFormField()) {String fileName = new File(item.getName()).getName();//下面的路径就是你要映射到target的路径String filePath = request.getServletContext().getRealPath("/") + "WEB-INF"+File.separator+"static" + File.separator + fileName;File storeFile = new File(filePath);// 在控制台输出文件的上传路径System.out.println(filePath);System.out.println("编码前的原文: " + fileName);//这一条在控制台打印可能会出现字符编码的问题,如浣撴浜哄憳淇℃伅.xlsx//这种是gbk编码,接下来就将gbk解码为utf-8byte[] gbkBytes = fileName.getBytes("gbk");for (byte b : gbkBytes) {System.out.print(Integer.toHexString(b & 0xff) + ",");}String gbkToUtf8 = new String(gbkBytes, "utf8");System.out.println("gbk编码,utf8解码后的文字: " + gbkToUtf8 + "\n" + "----------------------");// 保存文件到硬盘item.write(storeFile);request.setAttribute("message", "文件上传成功!");}}}} catch (Exception ex) {request.setAttribute("message", "文件上传失败!");}}
这样子字符编码就不会出现乱码
这样子写就可以实现上面的那种效果啦