You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 18 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. # spring-boot-demo-upload
  2. > 本 demo 演示了 Spring Boot 如何实现本地文件上传以及如何上传文件至七牛云平台。前端使用 vue 和 iview 实现上传页面。
  3. ## pom.xml
  4. ```xml
  5. <?xml version="1.0" encoding="UTF-8"?>
  6. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  8. <modelVersion>4.0.0</modelVersion>
  9. <artifactId>spring-boot-demo-upload</artifactId>
  10. <version>1.0.0-SNAPSHOT</version>
  11. <packaging>jar</packaging>
  12. <name>spring-boot-demo-upload</name>
  13. <description>Demo project for Spring Boot</description>
  14. <parent>
  15. <groupId>com.xkcoding</groupId>
  16. <artifactId>spring-boot-demo</artifactId>
  17. <version>1.0.0-SNAPSHOT</version>
  18. </parent>
  19. <properties>
  20. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  21. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  22. <java.version>1.8</java.version>
  23. </properties>
  24. <dependencies>
  25. <dependency>
  26. <groupId>org.projectlombok</groupId>
  27. <artifactId>lombok</artifactId>
  28. <optional>true</optional>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-web</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-test</artifactId>
  41. <scope>test</scope>
  42. </dependency>
  43. <dependency>
  44. <groupId>cn.hutool</groupId>
  45. <artifactId>hutool-all</artifactId>
  46. </dependency>
  47. <dependency>
  48. <groupId>com.qiniu</groupId>
  49. <artifactId>qiniu-java-sdk</artifactId>
  50. <version>[7.2.0, 7.2.99]</version>
  51. </dependency>
  52. </dependencies>
  53. <build>
  54. <finalName>spring-boot-demo-upload</finalName>
  55. <plugins>
  56. <plugin>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-maven-plugin</artifactId>
  59. </plugin>
  60. </plugins>
  61. </build>
  62. </project>
  63. ```
  64. ## UploadConfig.java
  65. ```java
  66. /**
  67. * <p>
  68. * 上传配置
  69. * </p>
  70. *
  71. * @package: com.xkcoding.upload.config
  72. * @description: 上传配置
  73. * @author: yangkai.shen
  74. * @date: Created in 2018/10/23 14:09
  75. * @copyright: Copyright (c) 2018
  76. * @version: V1.0
  77. * @modified: yangkai.shen
  78. */
  79. @Configuration
  80. @ConditionalOnClass({Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class})
  81. @ConditionalOnProperty(prefix = "spring.http.multipart", name = "enabled", matchIfMissing = true)
  82. @EnableConfigurationProperties(MultipartProperties.class)
  83. public class UploadConfig {
  84. @Value("${qiniu.accessKey}")
  85. private String accessKey;
  86. @Value("${qiniu.secretKey}")
  87. private String secretKey;
  88. private final MultipartProperties multipartProperties;
  89. @Autowired
  90. public UploadConfig(MultipartProperties multipartProperties) {
  91. this.multipartProperties = multipartProperties;
  92. }
  93. /**
  94. * 上传配置
  95. */
  96. @Bean
  97. @ConditionalOnMissingBean
  98. public MultipartConfigElement multipartConfigElement() {
  99. return this.multipartProperties.createMultipartConfig();
  100. }
  101. /**
  102. * 注册解析器
  103. */
  104. @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
  105. @ConditionalOnMissingBean(MultipartResolver.class)
  106. public StandardServletMultipartResolver multipartResolver() {
  107. StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
  108. multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());
  109. return multipartResolver;
  110. }
  111. /**
  112. * 华东机房
  113. */
  114. @Bean
  115. public com.qiniu.storage.Configuration qiniuConfig() {
  116. return new com.qiniu.storage.Configuration(Zone.zone0());
  117. }
  118. /**
  119. * 构建一个七牛上传工具实例
  120. */
  121. @Bean
  122. public UploadManager uploadManager() {
  123. return new UploadManager(qiniuConfig());
  124. }
  125. /**
  126. * 认证信息实例
  127. */
  128. @Bean
  129. public Auth auth() {
  130. return Auth.create(accessKey, secretKey);
  131. }
  132. /**
  133. * 构建七牛空间管理实例
  134. */
  135. @Bean
  136. public BucketManager bucketManager() {
  137. return new BucketManager(auth(), qiniuConfig());
  138. }
  139. }
  140. ```
  141. ## UploadController.java
  142. ```java
  143. /**
  144. * <p>
  145. * 文件上传 Controller
  146. * </p>
  147. *
  148. * @package: com.xkcoding.upload.controller
  149. * @description: 文件上传 Controller
  150. * @author: yangkai.shen
  151. * @date: Created in 2018/11/6 16:33
  152. * @copyright: Copyright (c) 2018
  153. * @version: V1.0
  154. * @modified: yangkai.shen
  155. */
  156. @RestController
  157. @Slf4j
  158. @RequestMapping("/upload")
  159. public class UploadController {
  160. @Value("${spring.servlet.multipart.location}")
  161. private String fileTempPath;
  162. @Value("${qiniu.prefix}")
  163. private String prefix;
  164. private final IQiNiuService qiNiuService;
  165. @Autowired
  166. public UploadController(IQiNiuService qiNiuService) {
  167. this.qiNiuService = qiNiuService;
  168. }
  169. @PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  170. public Dict local(@RequestParam("file") MultipartFile file) {
  171. if (file.isEmpty()) {
  172. return Dict.create().set("code", 400).set("message", "文件内容为空");
  173. }
  174. String fileName = file.getOriginalFilename();
  175. String rawFileName = StrUtil.subBefore(fileName, ".", true);
  176. String fileType = StrUtil.subAfter(fileName, ".", true);
  177. String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
  178. try {
  179. file.transferTo(new File(localFilePath));
  180. } catch (IOException e) {
  181. log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
  182. return Dict.create().set("code", 500).set("message", "文件上传失败");
  183. }
  184. log.info("【文件上传至本地】绝对路径:{}", localFilePath);
  185. return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", fileName).set("filePath", localFilePath));
  186. }
  187. @PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  188. public Dict yun(@RequestParam("file") MultipartFile file) {
  189. if (file.isEmpty()) {
  190. return Dict.create().set("code", 400).set("message", "文件内容为空");
  191. }
  192. String fileName = file.getOriginalFilename();
  193. String rawFileName = StrUtil.subBefore(fileName, ".", true);
  194. String fileType = StrUtil.subAfter(fileName, ".", true);
  195. String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
  196. try {
  197. file.transferTo(new File(localFilePath));
  198. Response response = qiNiuService.uploadFile(new File(localFilePath));
  199. if (response.isOK()) {
  200. JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());
  201. String yunFileName = jsonObject.getStr("key");
  202. String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;
  203. FileUtil.del(new File(localFilePath));
  204. log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
  205. return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
  206. } else {
  207. log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
  208. FileUtil.del(new File(localFilePath));
  209. return Dict.create().set("code", 500).set("message", "文件上传失败");
  210. }
  211. } catch (IOException e) {
  212. log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
  213. return Dict.create().set("code", 500).set("message", "文件上传失败");
  214. }
  215. }
  216. }
  217. ```
  218. ## QiNiuServiceImpl.java
  219. ```java
  220. /**
  221. * <p>
  222. * 七牛云上传Service
  223. * </p>
  224. *
  225. * @package: com.xkcoding.upload.service.impl
  226. * @description: 七牛云上传Service
  227. * @author: yangkai.shen
  228. * @date: Created in 2018/11/6 17:22
  229. * @copyright: Copyright (c) 2018
  230. * @version: V1.0
  231. * @modified: yangkai.shen
  232. */
  233. @Service
  234. @Slf4j
  235. public class QiNiuServiceImpl implements IQiNiuService, InitializingBean {
  236. private final UploadManager uploadManager;
  237. private final Auth auth;
  238. @Value("${qiniu.bucket}")
  239. private String bucket;
  240. private StringMap putPolicy;
  241. @Autowired
  242. public QiNiuServiceImpl(UploadManager uploadManager, Auth auth) {
  243. this.uploadManager = uploadManager;
  244. this.auth = auth;
  245. }
  246. /**
  247. * 七牛云上传文件
  248. *
  249. * @param file 文件
  250. * @return 七牛上传Response
  251. * @throws QiniuException 七牛异常
  252. */
  253. @Override
  254. public Response uploadFile(File file) throws QiniuException {
  255. Response response = this.uploadManager.put(file, file.getName(), getUploadToken());
  256. int retry = 0;
  257. while (response.needRetry() && retry < 3) {
  258. response = this.uploadManager.put(file, file.getName(), getUploadToken());
  259. retry++;
  260. }
  261. return response;
  262. }
  263. @Override
  264. public void afterPropertiesSet() {
  265. this.putPolicy = new StringMap();
  266. putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
  267. }
  268. /**
  269. * 获取上传凭证
  270. *
  271. * @return 上传凭证
  272. */
  273. private String getUploadToken() {
  274. return this.auth.uploadToken(bucket, null, 3600, putPolicy);
  275. }
  276. }
  277. ```
  278. ## index.html
  279. ```html
  280. <!doctype html>
  281. <html lang="en">
  282. <head>
  283. <meta charset="UTF-8">
  284. <meta name="viewport"
  285. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  286. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  287. <title>spring-boot-demo-upload</title>
  288. <!-- import Vue.js -->
  289. <script src="https://cdn.bootcss.com/vue/2.5.17/vue.min.js"></script>
  290. <!-- import stylesheet -->
  291. <link href="https://cdn.bootcss.com/iview/3.1.4/styles/iview.css" rel="stylesheet">
  292. <!-- import iView -->
  293. <script src="https://cdn.bootcss.com/iview/3.1.4/iview.min.js"></script>
  294. </head>
  295. <body>
  296. <div id="app">
  297. <Row :gutter="16" style="background:#eee;padding:10%">
  298. <i-col span="12">
  299. <Card style="height: 300px">
  300. <p slot="title">
  301. <Icon type="ios-cloud-upload"></Icon>
  302. 本地上传
  303. </p>
  304. <div style="text-align: center;">
  305. <Upload
  306. :before-upload="handleLocalUpload"
  307. action="/demo/upload/local"
  308. ref="localUploadRef"
  309. :on-success="handleLocalSuccess"
  310. :on-error="handleLocalError"
  311. >
  312. <i-button icon="ios-cloud-upload-outline">选择文件</i-button>
  313. </Upload>
  314. <i-button
  315. type="primary"
  316. @click="localUpload"
  317. :loading="local.loadingStatus"
  318. :disabled="!local.file">
  319. {{ local.loadingStatus ? '本地文件上传中' : '本地上传' }}
  320. </i-button>
  321. </div>
  322. <div>
  323. <div v-if="local.log.status != 0">状态:{{local.log.message}}</div>
  324. <div v-if="local.log.status === 200">文件名:{{local.log.fileName}}</div>
  325. <div v-if="local.log.status === 200">文件路径:{{local.log.filePath}}</div>
  326. </div>
  327. </Card>
  328. </i-col>
  329. <i-col span="12">
  330. <Card style="height: 300px;">
  331. <p slot="title">
  332. <Icon type="md-cloud-upload"></Icon>
  333. 七牛云上传
  334. </p>
  335. <div style="text-align: center;">
  336. <Upload
  337. :before-upload="handleYunUpload"
  338. action="/demo/upload/yun"
  339. ref="yunUploadRef"
  340. :on-success="handleYunSuccess"
  341. :on-error="handleYunError"
  342. >
  343. <i-button icon="ios-cloud-upload-outline">选择文件</i-button>
  344. </Upload>
  345. <i-button
  346. type="primary"
  347. @click="yunUpload"
  348. :loading="yun.loadingStatus"
  349. :disabled="!yun.file">
  350. {{ yun.loadingStatus ? '七牛云文件上传中' : '七牛云上传' }}
  351. </i-button>
  352. </div>
  353. <div>
  354. <div v-if="yun.log.status != 0">状态:{{yun.log.message}}</div>
  355. <div v-if="yun.log.status === 200">文件名:{{yun.log.fileName}}</div>
  356. <div v-if="yun.log.status === 200">文件路径:{{yun.log.filePath}}</div>
  357. </div>
  358. </Card>
  359. </i-col>
  360. </Row>
  361. </div>
  362. <script>
  363. new Vue({
  364. el: '#app',
  365. data: {
  366. local: {
  367. // 选择文件后,将 beforeUpload 返回的 file 保存在这里,后面会用到
  368. file: null,
  369. // 标记上传状态
  370. loadingStatus: false,
  371. log: {
  372. status: 0,
  373. message: "",
  374. fileName: "",
  375. filePath: ""
  376. }
  377. },
  378. yun: {
  379. // 选择文件后,将 beforeUpload 返回的 file 保存在这里,后面会用到
  380. file: null,
  381. // 标记上传状态
  382. loadingStatus: false,
  383. log: {
  384. status: 0,
  385. message: "",
  386. fileName: "",
  387. filePath: ""
  388. }
  389. }
  390. },
  391. methods: {
  392. // beforeUpload 在返回 false 或 Promise 时,会停止自动上传,这里我们将选择好的文件 file 保存在 data里,并 return false
  393. handleLocalUpload(file) {
  394. this.local.file = file;
  395. return false;
  396. },
  397. // 这里是手动上传,通过 $refs 获取到 Upload 实例,然后调用私有方法 .post(),把保存在 data 里的 file 上传。
  398. // iView 的 Upload 组件在调用 .post() 方法时,就会继续上传了。
  399. localUpload() {
  400. this.local.loadingStatus = true; // 标记上传状态
  401. this.$refs.localUploadRef.post(this.local.file);
  402. },
  403. // 上传成功后,清空 data 里的 file,并修改上传状态
  404. handleLocalSuccess(response) {
  405. this.local.file = null;
  406. this.local.loadingStatus = false;
  407. if (response.code === 200) {
  408. this.$Message.success(response.message);
  409. this.local.log.status = response.code;
  410. this.local.log.message = response.message;
  411. this.local.log.fileName = response.data.fileName;
  412. this.local.log.filePath = response.data.filePath;
  413. this.$refs.localUploadRef.clearFiles();
  414. } else {
  415. this.$Message.error(response.message);
  416. this.local.log.status = response.code;
  417. this.local.log.message = response.message;
  418. }
  419. },
  420. // 上传失败后,清空 data 里的 file,并修改上传状态
  421. handleLocalError() {
  422. this.local.file = null;
  423. this.local.loadingStatus = false;
  424. this.$Message.error('上传失败');
  425. },
  426. // beforeUpload 在返回 false 或 Promise 时,会停止自动上传,这里我们将选择好的文件 file 保存在 data里,并 return false
  427. handleYunUpload(file) {
  428. this.yun.file = file;
  429. return false;
  430. },
  431. // 这里是手动上传,通过 $refs 获取到 Upload 实例,然后调用私有方法 .post(),把保存在 data 里的 file 上传。
  432. // iView 的 Upload 组件在调用 .post() 方法时,就会继续上传了。
  433. yunUpload() {
  434. this.yun.loadingStatus = true; // 标记上传状态
  435. this.$refs.yunUploadRef.post(this.yun.file);
  436. },
  437. // 上传成功后,清空 data 里的 file,并修改上传状态
  438. handleYunSuccess(response) {
  439. this.yun.file = null;
  440. this.yun.loadingStatus = false;
  441. if (response.code === 200) {
  442. this.$Message.success(response.message);
  443. this.yun.log.status = response.code;
  444. this.yun.log.message = response.message;
  445. this.yun.log.fileName = response.data.fileName;
  446. this.yun.log.filePath = response.data.filePath;
  447. this.$refs.yunUploadRef.clearFiles();
  448. } else {
  449. this.$Message.error(response.message);
  450. this.yun.log.status = response.code;
  451. this.yun.log.message = response.message;
  452. }
  453. },
  454. // 上传失败后,清空 data 里的 file,并修改上传状态
  455. handleYunError() {
  456. this.yun.file = null;
  457. this.yun.loadingStatus = false;
  458. this.$Message.error('上传失败');
  459. }
  460. }
  461. })
  462. </script>
  463. </body>
  464. </html>
  465. ```
  466. ## 参考
  467. 1. Spring 官方文档:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#howto-multipart-file-upload-configuration
  468. 2. 七牛云官方文档:https://developer.qiniu.com/kodo/sdk/1239/java#5

一个用来深度学习并实战 spring boot 的项目,目前总共包含 66 个集成demo,已经完成 55 个。

Contributors (1)