栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot接收后端上传的图片

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot接收后端上传的图片

导入依赖

 
     commons-fileupload
     commons-fileupload
     1.3.3
 

controller

 package com.lixianhe.controller;
 ​
 import org.springframework.core.io.ClassPathResource;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 ​
 ​
 import java.io.*;
 import java.util.UUID;
 ​
 ​
 
 @RestController
 public class UploadController {
 ​
     @RequestMapping(value = "/load", method = RequestMethod.POST, consumes ="multipart/form-data")
     public String getFile(@RequestParam("file") MultipartFile file) throws IOException {
 ​
         System.out.println("收到请求");
         if (file.isEmpty()) {
             return "上传失败,请选择文件";
         }
         String fileName=file.getOriginalFilename();
         //String fileName = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
         System.out.println("文件名为:"+fileName);
         assert fileName != null;
         String suffixName = fileName.substring(fileName.lastIndexOf("."));
         System.out.println("文件的后缀名为:" + suffixName);
         String newfileName= UUID.randomUUID().toString()
                 .replaceAll("-", "")
                 .toUpperCase()
                 +System.currentTimeMillis()
                 +suffixName;
         System.out.println("新的名称->"+newfileName);
 ​
         ClassPathResource resource = new ClassPathResource("static");
 ​
         String path = resource.getFile().getAbsolutePath();
 ​
         File dest = new File(path+ "\" + newfileName);
         System.out.println(dest);
         try {
             file.transferTo(dest);
             System.out.println("上传成功");
             return newfileName;
         } catch (IOException e) {
             System.out.println("上传失败");
             System.out.println(e.getMessage());
         }
         return "上传失败!";
     }
 }

测试

设置请求头

设置请求数据是文件类型

结果:上传成功

 收到请求
 文件名为:aMXyhAzKyCJe9f9558bca12106c8360b89e900043b2d.png
 文件的后缀名为:.png
 新的名称->B7527AD5D1F34F80963CA9E593ECB66E1651811072581.png
 C:Users86131Desktophospitalhospitalhospitalhospital-usertargetclassesstaticB7527AD5D1F34F80963CA9E593ECB66E1651811072581.png
 上传成功
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862187.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号