标签:
//需要的jar包:
com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.io-1.4.0.jar
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class Params { public Params() { System.out.println("costructor...."); } @RequestMapping("/upload") public ModelAndView upload(String name, MultipartFile myFile, HttpServletRequest req)//形参名要与参数名相同 throws FileNotFoundException, IOException { System.out.println(name + "::" + myFile); String originName = myFile.getOriginalFilename(); String absPath = req.getServletContext().getRealPath("/uploads"); System.out.println(absPath); String fileName = UUID.randomUUID().toString() + "."+FilenameUtils.getExtension(originName); File file = new File(absPath, fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } IOUtils.copy(myFile.getInputStream(), new FileOutputStream(file)); return null; } }
//要在ApplicationContext中配置如下
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为1MB --> <property name="maxUploadSize"> <value>1048576</value> </property> </bean>
表单如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <form action="/upload.do" method="post" enctype="multipart/form-data"> 姓名:<input type="text" name="name"><br> 文件:<input type="file" name="myFile" ><br> <input type="submit"> </form> </body> </html>
标签:
原文地址:http://www.cnblogs.com/tabchanj/p/5697442.html