Eclipse+SprignBoot实现文件上传
生活随笔
收集整理的這篇文章主要介紹了
Eclipse+SprignBoot实现文件上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
項目搭建專欄:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/column/info/35688
實現
項目依賴中引入web依賴,則自動依賴文件上傳
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>引入thymeleaf依賴,實現上傳頁面
<!-- springboot整合thymeleaf --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>新建模板upload.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>upload test</title> </head> <body><form method="POST" enctype="multipart/form-data" action="/upload"><p><input type="file" name="file"/></p><p><input type="submit" value="上傳"/></p> </form> </body> </html>在項目src/main下新建webapp目錄,再新建upload目錄
找到全局配置文件aplication.properties
#設置單個文件上傳的文件大小 spring.servlet.multipart.max-file-size=10000000 #設置所有文件上傳的文件大小 spring.servlet.multipart.max-request-size=100000000?
新建Controller
package com.example.demo.controller;import java.io.File; import java.util.UUID;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile;@Controller public class UploadController {@RequestMapping("/toUpload")private String toUpload() {return "upload";}@RequestMapping(value="/upload",method=RequestMethod.POST)@ResponseBody//file要與表單上傳的名字相同public String? uploadFile(MultipartFile file,HttpServletRequest request) {try {//創建文件在服務器端存放路徑String dir = request.getServletContext().getRealPath("/upload");File fileDir = new File(dir);if(!fileDir.exists()) {fileDir.mkdirs();}//生成文件在服務器端存放的名字String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));String fileName=UUID.randomUUID().toString()+fileSuffix;File files = new File(fileDir+"/"+fileName);//上傳file.transferTo(files);} catch (Exception e) {e.printStackTrace();return "上傳失敗";}return "上傳成功";} }在啟動類中配置controller可被掃描
@SpringBootApplication(scanBasePackages= {"com.example.demo.controller","com.example.demo.service","com.example.demo.interceptor","com.example.demo.handler","com.example.demo.job","com.example.demo.email"})?
啟動項目,訪問
http://localhost:8080/toUpload
?
效果
上傳文件后
上傳成功
來到項目所在目錄
可以通過http://localhost:8080/upload/8981b1aa-c37d-4f05-887a-d01e5a5d692b.gif
訪問照片
源碼下載
https://download.csdn.net/download/badao_liumang_qizhi/11117921
總結
以上是生活随笔為你收集整理的Eclipse+SprignBoot实现文件上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样下载并使用soapUI进行webse
- 下一篇: MyBatisPlus介绍入门以及项目集