Springmvc实现文件上传的一般流程

1、导入spring的两个支持jar包,分别是:

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

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


2、修改springmvc配置文件,添加有关文件上传的配置


	
		
		
		
		
		
	
	
	
	
	
		
			
				
				error_fileupload
			
		
	


3、UpLoadController

package com.zn.controller;  
  
import java.io.File;  
import java.util.Date;  
  
import javax.servlet.http.HttpServletRequest;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.ModelMap;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.multipart.MultipartFile;  
  
@Controller  
public class UploadController {  
  
    @RequestMapping(value = "/upload.do")  
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {  
  
        System.out.println("开始");  
        String path = request.getSession().getServletContext().getRealPath("upload");  
        String fileName = file.getOriginalFilename();  
//        String fileName = new Date().getTime()+".jpg";  
        System.out.println(path);  
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);  
  
        return "result";  
    }  
  
}  

 






你可能感兴趣的:(Springmvc实现文件上传的一般流程)