Spring MVC框架:第九章:文件上传

2022-09-28 11:31:25 浏览数 (1)

第七章 文件上传 1.表单

代码语言:javascript复制
<form action="..." method="post" enctype="multipart/form-data">
    <input type="file" .../>
</form>

2.jar包

commons-fileupload-1.3.jar和commons-io-2.0.1.jar 3.配置CommonsMultipartResolver

代码语言:javascript复制
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 避免中文乱码 -->
    <property name="defaultEncoding" value="UTF-8"/>
</bean>

注意:id必须是multipartResolver 4.接收数据

①普通数据:和以前一样正常接收 ②文件数据:使用@RequestParam注解注入到MultipartFile类型的入参中

代码语言:javascript复制
@RequestMapping("/upload")
public String upload(@RequestParam("picture") MultipartFile picture) {
    return "...";
}

③MultiPartFile类型

实战案例: 结构图

web.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring-mvc.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <context:component-scan base-package="com.handlers"/>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    
    <!-- 配置multipart/form-data类型数据的解析器bean -->
    <!-- bean的id必须是:multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

</beans>

index.jsp

代码语言:javascript复制
<%@ 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="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
                你看我的新头像牛逼吗?
                <input type="file" name="picture" /><br/>
                <input type="submit" value="上传"/>
        </form>
    </body>
</html>

target.jsp

代码语言:javascript复制
<%@ 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>
<h1>Target</h1>
    <img src="${pageContext.request.contextPath }/myUpload/${requestScope.pictureName}"/>
</body>
</html>

UploadHandled.java

代码语言:javascript复制
package com.handlers;

import java.io.File;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadHandled {

    @Autowired
    private ServletContext servletContext;
    
    @RequestMapping("/upload")
    public String updoal(@RequestParam("picture") MultipartFile picture,Model model ) throws Exception, Exception {
            System.out.println(picture.getContentType());
            String originalFilename = picture.getOriginalFilename();
            String realPath = servletContext.getRealPath("/myUpload");
            picture.transferTo(new File(realPath "/" originalFilename));
            model.addAttribute("pictureName", originalFilename);
        return "target";
    }
}

0 人点赞