springMVC 文件上传(upload)

java

浏览数:1,041

2019-1-7

片段 1片段 2片段 3片段 4片段 5


maven导包,spring的包和下面这两个包

<properties>
    <commons.io.version>2.4</commons.io.version>
    <fileupload.version>1.2.1</fileupload.version>
</properties>
<dependencies>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>${fileupload.version}</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>${commons.io.version}</version>
    </dependency>
 </dependencies>


javaConfig配置springMVC

package com.amiu.java_config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[]{MvcConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        // TODO Auto-generated method stub
        return new String[]{"/"};
    }
    
}


MvcConfig

package com.amiu.java_config;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan("com.amiu")
public class MvcConfig extends WebMvcConfigurerAdapter{

    private static final Logger logger = Logger.getLogger(MvcConfig.class);
    
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipart = new CommonsMultipartResolver();
        commonsMultipart.setDefaultEncoding("UTF-8");//设置字符编码
        //commonsMultipart.setMaxUploadSizePerFile(5*1024*1024);//单个文件最大上传限制
        commonsMultipart.setMaxUploadSize(20*1024*1024);//设置最大上传大小
        try {
            //设置临时路径
            commonsMultipart.setUploadTempDir(new FileSystemResource("/tempImg"));
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return commonsMultipart;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
    
}


spring controller

package com.amiu.upload;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@RestController
public class ImgController {
    private static final Logger logger = Logger.getLogger(ImgController.class);
    //上传最大限制
    private long UPLOAD_FILE_MAX_SIZE = 5*1024*1024;
    private List<String> SUPPORT_IAMGE_SUFFIXList;
    //被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,
    //并且只会被服务器调用一次,类似于Serclet的inti()方法
    @PostConstruct
    void init(){
        SUPPORT_IAMGE_SUFFIXList = 
                new ArrayList<String>();
        SUPPORT_IAMGE_SUFFIXList.add("jpg");
        SUPPORT_IAMGE_SUFFIXList.add("png");
        SUPPORT_IAMGE_SUFFIXList.add("jpeg");
        SUPPORT_IAMGE_SUFFIXList.add("pdf");
    }
    @RequestMapping(value = "/img")
    public String uploadPic(MultipartHttpServletRequest request) {
        System.out.println("in imageUpload");
        //只获取image
        MultipartFile image = request.getFile("image");
        
        if(image == null) return "choice file please";
        
        if(image.getSize() > UPLOAD_FILE_MAX_SIZE) return "file to big,it must smaller than 5M";
        
        String orgFileName = image.getOriginalFilename();
        //文件格式后缀
        String fileSuffix = orgFileName.substring(orgFileName.indexOf('.')+1).toLowerCase();
        //判断文件格式
        if(!SUPPORT_IAMGE_SUFFIXList.contains(fileSuffix)) return "unsupport file format";
        
        String path = "E:/image/";
        String fileName = new Date().getTime()+fileSuffix;
        File localFile = new File(path+fileName);
        try {
            //spring提供的上传方法
            image.transferTo(localFile);
        } catch (IllegalStateException | IOException e) {
            logger.error(e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return "success: "+fileName;
    }

}


页面

<form action="/img" method="post" enctype="multipart/form-data">
        <input type="file" name="image"/>
        <input type="submit" value="上传"/>
</form>