天天看點

SpringMVC中采用簡潔的配置實作檔案上傳

檔案上傳我們一般會有兩種政策,一種是通過IO流上傳,還有一種是通過表單上傳,其實這兩種在用戶端實作起來都是很簡單的,在服務端處理會略有差别,個人感覺IO上傳代碼簡單,但是也有很多硬傷,還是表單上傳更合适。特别是如果我們的背景程式如果既面向移動端,又面向Web前端,那麼通過表單上傳無疑是最佳解決方案。OK,廢話不多說,我們來看看如何通過一個最簡單的配置來實作檔案的上傳。 

我們主要通過如下幾個步驟來實作這個功能:

1.引入依賴 

2.建立檔案上傳頁面 

3.配置SpringMVC 

4.Web配置 

5.編寫Controller

OK,按照這個步驟我們一步一步來看。

引入依賴

當然在引入依賴之前我們需要先建立一個被Maven管理的Web Project,建立方式我就不多說了。建立成功之後在SpringMVC架構的基礎之上再添加如下兩個依賴就行了:

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
 </dependency>      

兩個依賴庫,一個用來解決檔案上傳,一個簡化IO操作。

建立檔案上傳頁面

這個是一個簡單的jsp頁面,我在resources檔案夾中建立views檔案夾,在views檔案夾中建立index.jsp檔案。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>檔案上傳</title>
</head>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file" />
    <input type="submit" value="上傳" />
</form>
</body>
</html>      

這個頁面很簡單,沒啥好說的,注意action是upload就行了。

配置SpringMVC

這一步算是比較關鍵的一步,但是這裡隻有一個新Bean,我們先來看看類:

@Configuration
@EnableWebMvc
@ComponentScan("org.sang")
public class MVCConfig extends WebMvcConfigurerAdapter{
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("/index");
    }
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxUploadSize(1000000);
        return resolver;
    }
}      

這個類在前面幾篇部落格中已經反複說過好幾次了,這裡隻是多了一個multipartResolver方法,該方法用來提供一個MultipartResolver的Bean,該方法中主要根據業務需求對CommonsMultipartResolver進行配置,我這裡以限制上傳檔案大小為例。

Web配置

public class WebInit implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MVCConfig.class);
        context.setServletContext(servletContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }
}      

編寫Controller

@Controller
public class UploadController {
    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
    public String upload(MultipartFile file) {
        try {
            FileUtils.writeByteArrayToFile(new File("/home/sang/workspace/"+file.getOriginalFilename()),file.getBytes());
            return "上傳成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "上傳失敗";
        }
    }
}      

這裡通過Common-IO 中提供的相關方法,直接将上傳檔案的byte數組寫成檔案就行。 

這個時候運作項目,在浏覽器中打開index.jsp,如下: 

選擇檔案然後上傳即可在電腦的/home/sang/workspace目錄下看到上傳的檔案。