SpringBoot-图片上传

SpringBoot-图片上传

1. 准备

1.1 springboot上传文件大小配置

servlet:
      multipart:
        max-file-size: 128MB #上传文件总大值
        max-request-size: 10MB  #单个文件的最大值

1.2 在配置文件重配置上传地址
在进行文件上传时会存在上传到多个位置,可以通过如下配置进行区分,有效统一地址操作,避免不必要的误操作。

#文件上传操作
uploadFile:
  resourceHandler: /upload_img/ #请求 url 中的资源映射也是保存到数据库中的父级路径
  staticAccessPath: /upload_img/**
  location: /root/uploadFiles/

1.3 创建保存图片地址信息对象
由于可能会对图片进行上传后马上保存到后端数据库,于是建立了一个视图对象信息方式返回前端。

@Data
public class ToolesImagesVO {

	private Integer id;	// 自增id

	private String filePath;	  // 图片地址
}

2.图片上传

2.1 文件上传控制方法

@RestController
@RequestMapping("/files/")
@Api(value = "files", tags = "文件操作")
public class ToolesFilesUploadController {

	// 引用配置地址
	@Value("${uploadFile.resourceHandler}")
	private String resourceHandler;

	@Value("${uploadFile.location}")
	private String location;

	@Value("${uploadFile.productImagesPath}")
	private String productImagesPath;

	@ApiOperation(value = "图片上传", notes = "图片上传")
	@PostMapping(value = "/product/imageUpload", headers = "content-type=multipart/form-data")
	@ResponseBody
	public Object productImageUpload(@RequestParam(value = "images") MultipartFile images, HttpServletRequest request) throws Exception {
		if (StringUtils.isEmpty(images)) {
			return ResponseUtil.fail(BADARGUMENTVALUE, "上传图片为空!");
		}
		String fileName = images.getOriginalFilename();    // 文件名称
		String suffixName = fileName.substring(fileName.lastIndexOf("."));    // 图片后缀
		ToolesImagesVO vo = new ToolesImagesVO();
		// 判断文件后缀是否为后端默认的后缀名
		if (isImageFile(suffixName)) {
			fileName = UUID.randomUUID() + suffixName;    // 新图片名称
			String saveToPath = resourceHandler + productImagesPath + DateUtils.getDate() + "/";        // 域名访问的相对路径(通过浏览器访问的链接-虚拟路径)
			String realPath = location + productImagesPath + DateUtils.getDate() + "/";        // 真实路径,实际储存的路径
			String filepath = realPath + fileName;        // 储存文件的物理路径,使用本地路径储存
			FileUtils.uploadFile(images, filepath, realPath, fileName);    // 文件保存
			String basePath = HttpUtils.getBasePath(request);
			vo.setFilePath(basePath + saveToPath + fileName);
		}
		return ResponseUtil.ok(vo);
	}

	

	// 判断后缀
	private Boolean isImageFile(String fileName) {
		String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".bmp"};
		if (fileName == null) {
			return false;
		}
		fileName = fileName.toLowerCase();
		for (String type : img_type) {
			if (fileName.endsWith(type)) {
				return true;
			}
		}
		return false;
	}
}

2.2 文件上传实现

public class FileUtils extends org.apache.commons.io.FileUtils{
	 /**
    * 功能描述:文件上传
    *
    * @param: [file, filepath, realPath, fileName]
    * @author: Eggsy
    * @date: 2021-01-22 17:47:42
    * @return: boolean
    **/
    public static boolean uploadFile(MultipartFile file, String filepath, String realPath, String fileName){
		boolean flag = false;
		File dest = new File(filepath);		// 判断有没有对应的文件夹
		if (!dest.getParentFile().exists()){
			dest.getParentFile().mkdirs();
		}
		try {
			uploadFile(file.getBytes(),realPath,fileName);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	private static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if(!targetFile.exists()){
			System.out.println("创建文件夹");
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath+fileName);
		out.write(file);
		out.flush();
		out.close();
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值