springboot处理单个文件上传

1. 引入pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

2. 编写application.yml

server:
  port: 8082
spring:
  application:
    name: upload-service
  servlet:
    multipart:
      max-file-size: 5MB

3. 编写UploadService

package com.leyou.upload.service;

import com.leyou.upload.controller.UploadController;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author john
 * @date 2019/11/30 - 15:20
 */
@Service
public class UploadService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    //设置文件的contentType
    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpg", "image/jpeg", "image/gif");

    //设置文件存储的基路径
    private static final String BASE_PATH = "D:\\imooc\\project\\images\\";

    //设置文件返回的url
    private static final String IMAGE_URL = "http://image.leyou.com/";

    public String uploadImage(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();

        String ext = null;
        if (originalFilename == null || !originalFilename.contains(".")) {
            //图片名错误直接返回
            return null;
        }

        ext = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 1. 文件类型
        if (contentType == null) {
            LOGGER.info("文件{}获取不到contentType", originalFilename);
            return null;
        }

        if (!CONTENT_TYPES.contains(contentType.toLowerCase())) {
            LOGGER.info("文件上传失败: {},文件类型{}不合法", originalFilename, contentType);
            return null;
        }

        try {
            // 2. 校验文件的内容
            BufferedImage bufferImage = ImageIO.read(file.getInputStream());
            if (bufferImage == null || bufferImage.getWidth() <= 0 || bufferImage.getHeight() <= 0) {
                LOGGER.info("文件上传失败: {},文件内容不合法", originalFilename);
                return null;
            }

            //设置文件上传后的生成的新名字
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String newfileName = uuid + ext;

            //设置上传图片的实际存储目录
            String dirPath = DateFormatUtils.format(new Date(), "yyyyMMdd");
            String filepath = BASE_PATH + File.separator + dirPath;

            //创建新路径文件夹
            File targetFile = new File(filepath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }

            // 3. 保存到服务器
            file.transferTo(new File(filepath + File.separator + newfileName));
            // 4. 返回url路径

            return IMAGE_URL + dirPath + File.separator + newfileName;
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.info("文件{}上传失败:服务器异常 {}", originalFilename, e.getMessage());
            return null;
        }
    }
}


3. 编写UploadController

package com.leyou.upload.controller;

import com.leyou.upload.service.UploadService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author john
 * @date 2019/11/30 - 15:18
 */
@Controller
@RequestMapping("upload")
public class UploadController {
    @Autowired
    private UploadService uploadService;


    @PostMapping("image")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        String url = uploadService.uploadImage(file);

        if (StringUtils.isBlank(url)) {
            return ResponseEntity.badRequest().build();
        }

        return ResponseEntity.status(HttpStatus.CREATED).body(url);
    }
}

测试上传

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值