原理很简单:把文件写到nginx的静态资源目录中(一些传统项目直接写到项目的某一个目录中),然后通过单独图片域名访问

controller层代码

@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    UploadService uploadService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("image")
    public ResponseEntity<String> uploadFile(@RequestParam("file")MultipartFile file){
        //返回200 并且返回文件上传路径
        return ResponseEntity.ok(uploadService.uploadFile(file));
    }
}

service业务层


@Service
public class UploadService {
  //定义支持的文件类型
    private static final List<String> suffix= Arrays.asList("image/png","image/jpg");
    
    /**
     * 文件上传
     * @param file
     * @return
     */
    public String uploadFile(MultipartFile file) {

        try {
            //1校验文件类型
            String fileType = file.getContentType();
            if (!suffix.contains(fileType)){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //2校验文件内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read==null){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //3.保存图片
              //3.1 生成保存目录 保存到nginx的html文件中 ,这样可以通过nginx来直接访问
            File dir =new File("G:\\nginx-1.12.2\\html");
            if (!dir.exists()) {
                dir.mkdirs();
            }
              //3.2 保存图片
            file.transferTo(new File(dir,file.getOriginalFilename()));
              //3.3 拼接图片地址
            String imageUrl="http://image.leyou.com/"+file.getOriginalFilename();
            return imageUrl;

        } catch (Exception e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

    }
}

fastdfs方法实现文件上传

1.首先引入依赖
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
</dependency>
2.引入配置类纯java配置
@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {
 }
3.编写fastdfs配置文件的属性,yml文件的格式
fdfs:
  so-timeout: 2500
  connect-timeout: 600
  thumb-image: # 缩略图
    width: 60
    height: 60
  tracker-list: # tracker地址
    - 192.168.58.101:22122

4.改造传统方式上传的service层 实现fastdfs方式文件的上传
@Service
public class UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");

    @Autowired
    FastFileStorageClient storageClient;

    public String upload(MultipartFile file) {
        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType();
            if (!suffixes.contains(type)) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            // 2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }

            // 2、将图片上传到FastDFS
            // 2.1、获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 2.2、上传
            StorePath storePath = this.storageClient.uploadFile(
                    file.getInputStream(), file.getSize(), extension, null);
            // 2.3、返回完整路径
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }
    }
}
6.如果业务是通过nginx转发的,也就是文件上传通过nginx代理了,还需要在nginx中配置最大文件上传大小
 在nginx中的http下,添加配置:client_max_body_size 10M;

7.最后测试成功!