springboot图片上传

• application.yml

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

• uploadController.java

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;

/**
 * 文件上传
 */
@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);
        return StringUtils.isBlank(url)
                ? ResponseEntity.badRequest().build()
                : ResponseEntity.status(HttpStatus.CREATED).body(url);
    }

}

• uploadService.java

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.List;

/**
 * 文件上传
 */
@Service
public class UploadServiceImpl implements UploadService {
    //支持的图片类型
    private static final List<String> CONTENT_TYPE = Arrays.asList("image/gif", "image/jpeg","image/png");
    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    @Override
    public String uploadImage(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        //建议文件类型
        String contentType = file.getContentType();
        if (!CONTENT_TYPE.contains(contentType)) {
            LOGGER.info("文件类型不合法:{}", originalFilename);
            return null;
        }
        try {
            //检验文件内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                LOGGER.info("文件内容不合法:{}", originalFilename);
                return null;
            }
            //保存文件
            file.transferTo(new File("D:\\Code\\JavaCode\\leyou\\uploadImage\\" + originalFilename));
        } catch (IOException e) {
            LOGGER.error("服务器内部错误->:{}", originalFilename);
            e.printStackTrace();
        }
        //返回图片路径
return "http://**.***.com/" + originalFilename; } }
posted @ 2020-02-25 14:54  朱思年  阅读(1524)  评论(0编辑  收藏  举报