SpringBoot实现简单文件上传功能
通过 SpringBoot 实现了表单下的文件上传,前后端分离情况下的文件上传。本案例不连接数据库,只做基本的文件上传操作。
在 SpringBoot 中不需要额外导入其他依赖,正常引入即可。
后端 controller 的写法
package com.dailyblue.java.controller; import org.springframework.util.ResourceUtils;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.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;import java.io.File;import java.io.IOException; @RestController@RequestMapping("/upload")public class UploadController { @PostMapping public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception { // file:上传文件 // 获取到 images 的具体路径 // String realPath = request.getRealPath("images"); String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/images"; System.out.println("上传的文件地址是:" + realPath); // 服务器中对应的位置 // 产生唯一的文件名称 String fileName = UUID.getUUid(); // 获取到文件后缀 String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); File src = new File(realPath, fileName + fileType); // 将file文件传递到src去 file.transferTo(src); return "images/" + fileName + fileType; }}这里只做了简单的文件上传,没有限制文件类型。
前端写法
这里分为两种写法,一种是常用的表单提交,另一种是当下较火的 Vue 上传方式。
表单写法
<form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <button>上传</button></form>Vue 写法
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><div id="app"> <img :src="'http://localhost:8081/'+img" v-show="flag"/> <input type="file" @change="changeImg"/> <button @click="upload">Vue 上传</button></div></body></html><script src="js/vue.min.js"></script><script src="js/axios.min.js"></script><script> new Vue({ el: '#app', data: { file: null, img: '', flag: false }, methods: { changeImg(event) { this.file = event.target.files[0]; }, upload() { // 表单数据 let data = new FormData(); data.append('file', this.file); // 定义发送格式 let type = { headers: { 'Content-Type': 'multipart/form-data' } } axios.post('http://localhost:8081/upload', data, type) .then((response) => { this.img = response.data; this.flag = true; }); } } });</script>以上就是本文的全部内容。
参考文章:http://blog.ncmem.com/wordpress/2023/11/21/springboot%e5%ae%9e%e7%8e%b0%e7%ae%80%e5%8d%95%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%8a%9f%e8%83%bd/
欢迎入群一起讨论

浙公网安备 33010602011771号