Spring Boot实现图片上传功能

作者:flyfree丶 时间:2023-05-17 05:06:05 

本文实例为大家分享了Spring Boot图片上传的具体代码,供大家参考,具体内容如下


package com.clou.inteface.domain.web.user;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
* 文件上传
* @author Fly
*
*/
@RestController
public class FileUpload {

/**
* 用户管理 -> 业务层
*/
@Autowired
private SUserService sUserService;

/**
* 文件上传根目录(在Spring的application.yml的配置文件中配置):<br>
* web:
* upload-path: (jar包所在目录)/resources/static/
*/
@Value("${web.upload-path}")
private String webUploadPath;

/**
* ResultVo是一个对象,包含:
* private int errorCode;
* private String errorMsg;
* private Integer total;
* private Object data;
*/

/**
* 基于用户标识的头像上传
* @param file 图片
* @param userId 用户标识
* @return
*/
@PostMapping(value = "/fileUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResultVo fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("userId") Integer userId) {
ResultVo resultVo = new ResultVo();
if (!file.isEmpty()) {
if (file.getContentType().contains("image")) {
try {
 String temp = "images" + File.separator + "upload" + File.separator;
 // 获取图片的文件名
 String fileName = file.getOriginalFilename();
 // 获取图片的扩展名
 String extensionName = StringUtils.substringAfter(fileName, ".");
 // 新的图片文件名 = 获取时间戳+"."图片扩展名
 String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
 // 数据库保存的目录
 String datdDirectory = temp.concat(String.valueOf(userId)).concat(File.separator);
 // 文件路径
 String filePath = webUploadPath.concat(datdDirectory);

File dest = new File(filePath, newFileName);
 if (!dest.getParentFile().exists()) {
 dest.getParentFile().mkdirs();
 }
 // 判断是否有旧头像,如果有就先删除旧头像,再上传
 SUser userInfo = sUserService.findUserInfo(userId.toString());
 if (StringUtils.isNotBlank(userInfo.getUserHead())) {
 String oldFilePath = webUploadPath.concat(userInfo.getUserHead());
 File oldFile = new File(oldFilePath);
 if (oldFile.exists()) {
 oldFile.delete();
 }
 }
 // 上传到指定目录
 file.transferTo(dest);

// 将图片流转换进行BASE64加码
 //BASE64Encoder encoder = new BASE64Encoder();
 //String data = encoder.encode(file.getBytes());

// 将反斜杠转换为正斜杠
 String data = datdDirectory.replaceAll("\\\\", "/") + newFileName;
 Map<String, Object> resultMap = new HashMap<>();
 resultMap.put("file", data);
 resultVo.setData(resultMap);
 resultVo.setError(1, "上传成功!");
} catch (IOException e) {
 resultVo.setError(0, "上传失败!");
}
} else {
resultVo.setError(0, "上传的文件不是图片类型,请重新上传!");
}
return resultVo;
} else {
resultVo.setError(0, "上传失败,请选择要上传的图片!");
return resultVo;
}
}

}

以上代码需配置SUserService,一个业务层接口;

一个ResultVo对象,属性已给出;

一个基于Spring Boot的 .yml配置文件的配置。 

访问图片的时候,需要配置.yml文件

spring:

#配置http访问服务器图片的路径
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}

然后基于服务的IP与端口,http//IP:port/resources/static/图片路径(图片名)

更多精彩内容,请点击 《spring上传下载专题》进行深入学习和研究。

标签:Spring,Boot,上传
0
投稿

猜你喜欢

  • Java中四种访问权限资料整理

    2021-12-04 13:23:58
  • c# 如何实现代码生成器

    2023-11-13 19:23:35
  • Android 使用gradle打包Assets目录的案例

    2023-08-05 22:29:45
  • c#分页读取GB文本文件实例

    2021-09-13 10:18:39
  • Java使用pulsar-flink-connector读取pulsar catalog元数据代码剖析

    2023-11-05 17:25:41
  • Spring中的事务隔离级别和传播行为

    2022-07-21 18:18:24
  • C#发送邮箱实现代码

    2022-04-16 11:57:57
  • springcloud Zuul动态路由的实现

    2021-10-07 06:15:40
  • Spring中的两种代理JDK和CGLIB的区别浅谈

    2023-01-04 19:05:05
  • 使用SpringMVC的@Validated注解验证的实现

    2023-09-20 19:49:55
  • 浅谈Java堆外内存之突破JVM枷锁

    2022-10-19 19:46:50
  • Android 优雅的实现通用格式化编辑

    2023-02-08 05:24:02
  • Java正则验证电话,手机,邮箱,日期,金额的方法示例

    2021-06-25 22:37:46
  • MyBatis动态SQL标签的用法详解

    2021-07-24 10:38:56
  • C#图表算法之有向图

    2021-11-25 14:50:57
  • C++类和对象之类的6个默认成员函数详解

    2022-01-05 13:50:35
  • Spring boot+beetl+i18n国际化处理的方法

    2023-07-22 00:36:31
  • Android实现屏幕录制功能

    2022-10-29 15:26:36
  • Java创建子线程的两种方法

    2023-11-24 07:00:05
  • C# 对象映射的高性能方案

    2021-09-22 08:03:19
  • asp之家 软件编程 m.aspxhome.com