SpringBoot+Vue自定义文件名并上传
由于文件或图片上传时,文件名不是自己想要的,这时候就需要在前端修改好文件名再上传,这样可以避免重名的情况发生.
前端
直接上代码
-
<el-upload class="upload-demo" name="file" action="http://localhost:8080/person/upload" :on-success="handleSuccess" :on-error="handleError" :on-progress="handleProgress" :before-upload="beforeUpload" list-type="picture"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload>
-
action
就是后端接收文件的接口,改成自己的就可以 -
文件改名
-
<script> export default{ beforeUpload(file) { console.log('file') const timeStamp = new Date() - 0 console.log([file]) console.log(file) //这里的第二个参数就是自己要改的名字,这里是以用户的名字命名的,也可以用随机数或者时间戳来命名 const copyFile = new File([file], `${this.dataForm.username}`) this.uploadFile(copyFile) return false }, uploadFile(file) { const formdata = new FormData() formdata.append('lbf-file-upload', file) //提交的属性名是 lbf-file-upload,后端接收时一定要按照这个参数来接收 formdata.append('name', 'lbf-file-upload') this.postForm(formdata) }, postForm(formdata) { axios.post(`http://localhost:8080/person/upload`, formdata).then(({data}) => { console.log(data) if (data.code === '200') { // do something this.$message.success(data.msg) } else { this.$message.error(data.msg || data.msg || '文件上传失败') } }).catch((err) => { this.$message.error(err.msg || '文件上传失败') }) }, } </script>
-
默认是选择完文件后就自动上传,如果不想自动上传,可以吧
:auto-upload="false"
,然后添加一个确定上传的按钮,<el-button @click='submitUpload'>确定上传</el-button>
,submitUpload()方法this.$refs.upload.submit()
-
<el-upload class="upload-demo" name="file" action="http://localhost:8080/person/upload" :on-success="handleSuccess" :on-error="handleError" :on-progress="handleProgress" :auto-upload="false"` :before-upload="beforeUpload" list-type="picture"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button @click='submitUpload'>确定上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> <script> export default { data() { return {} }, methods: { submitUpload() { //提交 this.$refs.upload.submit(); }, } } </script>
前端完成,开始搞后端
SpringBoot后端
-
@Service public class PersonService{ /** * 上传 * * @param multipartFile multipart * @return object */ public Object upload(@NotNull MultipartFile multipartFile) { InputStream inputStream = null; BufferedOutputStream bos = null; try { //这里的文件名就是前端自定义的用户名 final String name = multipartFile.getOriginalFilename(); log.info("fileName = " + name); inputStream = multipartFile.getInputStream(); //保存到指定地址 bos = new BufferedOutputStream(new FileOutputStream("D:\\Code\\clone\\低代码平台\\healthcode\\qrCode\\" + name + ".jpg")); byte[] bytes = new byte[1024]; int len; while ((len = inputStream.read(bytes)) != -1) { bos.write(bytes, 0, len); } File file = new File("D:\\Code\\clone\\低代码平台\\healthcode\\qrCode\\" + name + ".jpg"); //获取文件的绝对路径 final String absolutePath = file.getAbsolutePath(); log.debug("图片绝对路径 = " + absolutePath); return "图片上传完成"; } catch (IOException e) { log.error(e.getMessage()); return "上传失败 " + e.getMessage(); } finally { try { assert bos != null; bos.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } @RestController public class PersonController{ @Resource private PersonService personService; @RequestMapping("/upload") //@RequestParam("lbf-file-upload") 请求参数,务必和前端传过来的请求参数名一致 public Object upload(@RequestParam("lbf-file-upload") MultipartFile multipartFile) { log.info("文件上传"); if (ObjectUtil.isNotNull(multipartFile)) { final Object upload = personService.upload(multipartFile); return new Result("200", (String) upload, upload); } return new Result().err("4444", "文件不能为空", null); } }
-
这样就上传完成啦