package com.deepwise.deepwise.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author zlw
 * @date 2018/11/9
 * @description
 */
@RestController
public class MyController {

    private static final String PATH = "/images6666";
    private static final int MAX_IMAGE_NUM = 500;

    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public Integer upload(@RequestParam("file") MultipartFile file) throws IOException {

        File folder = new File(PATH);
        if (countFileNumber(folder) > MAX_IMAGE_NUM) {
            return MAX_IMAGE_NUM;
        }

        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            InputStream is = file.getInputStream();

            if(!folder.exists()){
                folder.mkdir();
            }
            /*
            //方式一
            Files.copy(is, Paths.get(folder.getAbsolutePath() + File.separator + fileName),
                    StandardCopyOption.REPLACE_EXISTING);
            */
            //========================
            //方式二
            File uploadFile = new File(folder.getAbsolutePath() + File.separator + fileName);
            try (BufferedOutputStream outputStream = new BufferedOutputStream(
                    new FileOutputStream(uploadFile))) {
                outputStream.write(file.getBytes());
            }
            //========================
        }
        return countFileNumber(folder);
    }

    /**
     * 统计当前目录下的文件个数
     * @param directory,这里的参数也可以换成string类型,直接给出文件夹路径
     * @return
     */
    private int countFileNumber(File directory){
        if (!directory.isDirectory()){
            return 0;
        }
        return directory.listFiles().length;
    }

}

 

package com.deepwise.deepwise.config;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.MultipartConfigElement;

/**
 * @author zlw
 * @date 2018/11/9
 * @description
 */
@Configuration
public class ImageConfig extends WebMvcConfigurerAdapter {
    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大KB,MB
        factory.setMaxFileSize("2MB");
        //设置总上传数据总大小
        factory.setMaxRequestSize("10MB");
        return factory.createMultipartConfig();
    }
}

 

11-13 11:31