springboot实现简单的文件上传功能
pom里面只需要配置一个spring-boot-starter-web就行了
最简易的前端
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>文件上传</h1> <form action="http://localhost:8080/file" method="post" enctype="multipart/form-data"> 文件名称:<input name="fileImage" type="file"/><br> <input type="submit" value="提交"/> </form> </body>
简单的后端代码:
package com.ws.upload_doc.controller; /** * @author 王顺 * @date 2021/5/31 - 0:10 */ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; @RestController public class FileController { // http://localhost:8080/file @RequestMapping("/file") public String fileUpload(MultipartFile fileImage) throws IOException { System.out.println(fileImage.getOriginalFilename()); //固定保存在本地的路径:imagePathRoot final String imagePathRoot = "F:\\casual2\\"; //对固定路径进行操作 File file = new File(imagePathRoot); //判断文件夹是否存在,没有就去创建 if (!file.exists()) { file.mkdirs(); } //获得原来的图片名字 String fileName = fileImage.getOriginalFilename(); //获取图片的类型jpg or png String fileType = fileName.substring(fileName.lastIndexOf(".")); //创建一个uuid全世界唯一 String uuid = UUID.randomUUID().toString().replace("-", ""); //使用原名字+uuid+图片类型构成 保存在本地的文件名字 String imageFilePath = imagePathRoot + uuid + fileType; //将原来的文件保存到新的地址文件夹里去 fileImage.transferTo(new File(imageFilePath)); return "upload ok"; } }
这里要特地介绍一个新朋友:MultipartFile
-
MultipartFile这个类主要是来实现以表单的形式进行文件上传功能。
-
常用方法:
-
getOriginalFileName方法获取的是文件的完整名称,包括文件名称+文件拓展名。
-
getContentType方法获取的是文件的类型,注意是文件的类型,不是文件的拓展名。
-
法:
-
getOriginalFileName方法获取的是文件的完整名称,包括文件名称+文件拓展名。
-
getContentType方法获取的是文件的类型,注意是文件的类型,不是文件的拓展名。
-
transferTo方法用来将接收文件传输到给定目标路径,会抛出IOException、IllegalStateException异常。该方法在实际项目开发中使用较少。