Spring MVC文件上传

Spring MVC文件上传

1、file.jsp。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
  <form method="post" action="./file/upload.do" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择上传的文件" /> <input
      type="submit" value="提交" />
  </form>
</body>
</html>

2、控制器。

package com.ssm.cts.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

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;

/**
 * CopyRright (c)2018-2028: chanpinxue.cn 
 * Project: cts 
 * Module Name: FileController
 * Comments: 控制器
 * JDK version used: JDK1.8 
 * Author: jzh 
 * Create Date: 2018-10-30
 * Modified By: jzh 
 * Modified Date: 2018-10-30
 * Why & What is modified:
 * Version: <1.0>
 */

//注解@Controller表示它是一个控制器
@Controller("fileController")
//表明当请求的URI在/file下的时候才有该控制器响应
@RequestMapping("/file")
public class FileController {

  @RequestMapping(path="/upload")
  public void upload(@RequestParam MultipartFile uploadFile, HttpServletRequest request) throws Exception {
    // 获取upload的绝对路径
    String realPath = request.getServletContext().getRealPath("upload");
    //System.out.println(realPath);
    
    // 获取上传文件名
    String fileName = uploadFile.getOriginalFilename();
    //System.out.println(fileName);
    
    Date dNow = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
    String saveName = formatter.format(dNow) + fileName.substring(fileName.lastIndexOf("."));
    
    // 开始上传
    //uploadFile.transferTo(new File(realPath, uploadFile.getOriginalFilename()));
    uploadFile.transferTo(new File(realPath, saveName));
  }
}

3、spring配置文件applicationContext.xml。

  <!-- 文件上传 -->
<bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- maxUploadSize按单位Byte计算 -->
  <property name="maxUploadSize" value="83886080" />
  <property name="defaultEncoding" value="UTF-8" />
</bean>

 

发表回复

您的电子邮箱地址不会被公开。