vue+spring boot上传文件(图片)
1.spring boot 中后台接收
这里以图片上传为例 1.1.在前台上传图片之后,核心思想就是把前台的文件存储到本地之中,文件的路径存储在数据库之中。 下面是在spring boot框架下,后台完成的接收图片和存地址到数据库之中的方法。
package com.financeloan.vue.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.financeloan.vue.util.UuidUtil; @CrossOrigin//解决跨域问题 @RestController @RequestMapping("/file") public class FileController { @RequestMapping("/upload") public String FileUpdate (HttpServletRequest request,MultipartFile file) { //表示获得服务器的绝对路径 String str=request.getServletContext().getRealPath("/images/"); //得到上传时的文件名字 String originalname=file.getOriginalFilename(); //substring(originalname.lastIndexOf(".")截取图片名后缀 String newName= originalname.substring(originalname.lastIndexOf(".")); //利用UUidUtil工具类生成新的文件名字 newName =UuidUtil.get32UUID()+newName; System.out.println(newName); System.out.println(str); File newFile=new File(str,newName); //获得文件目录,判断是否存在 if(!newFile.getParentFile().exists()) { //如果path路径不存在,创建一个文件夹,存在则使用当前文件夹 newFile.getParentFile().mkdirs(); } try { //保存文件到指定路径之中 file.transferTo(newFile); } catch (IllegalStateException | IOException e) { e.printStackTrace(); } System.out.println("str"+str+"newName"+newName); return str+newName; } }
这是后台接收的上传文件进行的操作
1.2前台就相对简单一些 拿vue界面当例子(其他页面也可以,基本差不多)
产品图片:<Upload action=http://localhost//file/upload :on-success=uploadSuccess> <i-button icon="ios-cloud-upload-outline">上传文件</i-button> </Upload>
这是iview的一个组件,其他样式可以参照iview官网进行设置
//返回图片存储的路径 uploadSuccess(res,file){ console.log(res) this.productImg=res; },
上传之后返回存储的路径,在把图片路径和其他的内容一起添加到数据库之中 这是插入数据库中的路径