SpringMVC文件上传

阅读更多
1. SpringMvc单文件上传

2. SpringMvc多文件上传

新建项目SpringMvc04

导入fileupload jar包

com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.io-1.4.0.jar

FileUploadController.java

package com.andrew.controller;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {
    @RequestMapping("/upload")
    public String uploadFile(@RequestParam("file1") MultipartFile file1, HttpServletRequest request) throws Exception {
        String filePath = request.getServletContext().getRealPath("/");
        System.out.println(filePath);
        file1.transferTo(new File(filePath + "upload/" + file1.getOriginalFilename()));
        return "redirect:success.html";
    }
    @RequestMapping("/upload2")
    public String uploadFiles(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception {
        String filePath = request.getServletContext().getRealPath("/");
        System.out.println(filePath);
        for (MultipartFile file : files) {
            file.transferTo(new File(filePath + "upload/" + file.getOriginalFilename()));
        }
        return "redirect:success.html";
    }
}

spring-mvc.xml




    
    

    
    
        
        
    
    
          
        
    


web.xml



    SpringMvc04
    
        index.html
    

    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:spring-mvc.xml
        
    
    
        springmvc
        *.do
    


index.html





Insert title here


上传文件
文件一
文件二
success.html Insert title here 上传成功! http://localhost:8080/SpringMvc04/index.html 运行结果: http://localhost:8080/SpringMvc04/upload.do http://localhost:8080/SpringMvc04/upload/dd.jpg http://localhost:8080/SpringMvc04/upload2.do http://localhost:8080/SpringMvc04/upload/d1.jpg http://localhost:8080/SpringMvc04/upload/d2.jpg

你可能感兴趣的:(Java,SpringMVC)