文件上传

文件上传

文件上传需要使用以下两个依赖包(同样需要引入到项目依赖中):

  • commons-fileupload-1.3.3.jar
  • commons-io-2.6.jar

下载地址:http://note.youdao.com/noteshare?id=a0c15f123f963aca3904e3f0530689d4&sub=F612D7D8E4854B658C50BCCB5DDFA996

servlet.xml 配置

servlet.xml 中配置文件上传解析器及最大上传大小:

<!-- upload settings -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="102400000"></property>
</bean>Code language: HTML, XML (xml)

控制器方法

增加一个 upload 方法来处理上传:

@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest req) throws Exception{
    MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
    MultipartFile file = mreq.getFile("file");
    String fileName = file.getOriginalFilename();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String path = req.getSession().getServletContext().getRealPath("/") + "upload/";
    File file1 = new File(path);
    if(!file1.exists())
    {
        Boolean aa = file1.mkdir(); // true
    }
    System.out.println(path);
    FileOutputStream fos = new FileOutputStream(path + sdf.format(new Date()) + fileName.substring(fileName.lastIndexOf('.')));
    fos.write(file.getBytes());
    fos.flush();
    fos.close();

    return "hello";
}

@RequestMapping("/upload")
public String upload(){
    return "upload";
}Code language: JavaScript (javascript)

上传视图(upload.jsp)

<%@ 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="" method="post" enctype="multipart/form-data">
          <input type="file" name="file"><br>
          <input type="submit" value="submit">
      </form>
</body>
</html>Code language: HTML, XML (xml)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注