MyBatis+SpringMVC+SpringBootspring+springmvc+mybatis(SSM)

Spring4 MVC单文件上传-写法1

2018-03-04  本文已影响28人  养码哥

核心代码:

 `package controller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream; 
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class UserinfoController {
@RequestMapping(value = "upload")
public String loginMethod(MultipartHttpServletRequest request)
        throws IOException {
    String username = request.getParameter("username");
    System.out.println("username=" + username);

    MultipartFile file = request.getFile("uploadFile");
    String uploadFileName = file.getOriginalFilename();
    System.out.println("【文件名】" + uploadFileName);

    InputStream fileStream = file.getInputStream();

    String uploadPath = request.getSession().getServletContext()
            .getRealPath("/upload");

    File destination = new File(uploadPath, uploadFileName);
    FileUtils.copyInputStreamToFile(fileStream, destination);
    return "index.jsp";
  }
}
`

index.jsp

`<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="upload.spring" method="post" enctype="multipart/form-data">
    username:<input type="text" name="username"><br />
             要上传的文件:<input type="file" name="uploadFile"><br />
     <input type="submit" value="开始上传"><br />
</form>
</html>`

springMVC配置详情:文件上传最大为2GB

`<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="2048000000" />
</bean>
`

如果不在xml中添加上面的配置会出现异常。如图


另外为了解决上传文件时单行文本域有乱码的问题,所以还需要在web.xml中声明编码过滤器,代码如下

`  <filter>
    <filter-name>encodefilter  过滤器名称</filter-name>
    <filter-class>  org.springframework.web.filter.CharacterEncodingFilter 过滤器的完全限定名</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodefilter  过滤器名称</filter-name>
    <url-pattern>/*  需要过滤的页面地址</url-pattern>
</filter-mapping>`

上一篇下一篇

猜你喜欢

热点阅读