004 springboot文件上传

  关于文件上传,在spring cloud会再经过配置文件的处理,在spring boot则不需要,在这里写一个文件上传的接口。

  单文件上传,如果以后写多文件上传再进行补充。

1.文件目录

  

2.控制器程序

package com.jun.file.controller;

import com.jun.file.service.UpLoadFileService;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
public class UpLoadFileController {
    @Autowired
    private UpLoadFileService upLoadFileService;
    @PostMapping("/upload/img")
    public String uploadImg(@RequestParam("file") MultipartFile file){
        int count=upLoadFileService.upLoadImg(file);
        return "success";
    }

}

 

3.服务方法

package com.jun.file.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 这个类用于文件的上传
 */
@Service
public class UpLoadFileService {
    public int upLoadImg(MultipartFile file){
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String name = UUID.randomUUID().toString();
        fileName = name+suffixName;
        String path = "E:/javaImg/test/";
        String path_img = path+fileName;
        File dest = new File(path_img);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

  

4.测试

  

 

原文地址:https://www.cnblogs.com/juncaoit/p/11188765.html