Spring MVC 文件上传 Maven

阅读更多
FileUploadController.java

package cn.com.songjy.fileupload.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class FileUploadController implements ServletContextAware{
	
	private ServletContext servletContext;
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	
	@RequestMapping(value = "/file.do", method = RequestMethod.POST)
	public String fileUpload(
			@RequestParam("up1") MultipartFile multipartFile,
			@RequestParam("up2") CommonsMultipartFile commonsMultipartFile) throws Exception{
		String path = servletContext.getRealPath("/");
		if(multipartFile.isEmpty()){
			System.out.println("方式一没有选择文件");
		}else{
			String fileName = "way1"+multipartFile.getOriginalFilename();
			File file = new File(path+fileName);
			multipartFile.transferTo(file);
			
			System.out.println("方式一文件名:"+fileName);
			System.out.println("方式一文件路径:"+file.getPath());
			System.out.println("方式一文件后缀名:"+FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
		}
		
		if(commonsMultipartFile.isEmpty()){
			System.out.println("方式二没有选择文件");
		}else{
			String fileName = "way1"+commonsMultipartFile.getOriginalFilename();
			File file = new File(path+fileName);
			commonsMultipartFile.getFileItem().write(file);
			
			System.out.println("方式二文件名:"+fileName);
			System.out.println("方式二文件路径:"+file.getPath());
			System.out.println("方式二文件后缀名:"+FilenameUtils.getExtension(commonsMultipartFile.getOriginalFilename()));
		}
			
		return "file";
	}
	
	@RequestMapping(value = "/fileIndex.do", method = RequestMethod.GET)
	public String fileIndex(){
		return "file";
	}

}


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>




Spring FileUpload




  • songjy-fileupload-1.0-src.zip (27 KB)
  • 下载次数: 137
  • songjy-fileupload-1.0.zip (7 MB)
  • 下载次数: 116

你可能感兴趣的:(Spring MVC 文件上传 Maven)