加深spring上传文件

上传文件的详解

创建控制层,上传文件:

@Controller
public class MyController {
    @PostMapping("/myUpload")
    public String upload(HttpServletRequest request) {
        String upload = request.getServletContext().getRealPath("/upload");
        File file = new File(upload);
        if (!file.exists()) file.mkdirs();
        try {
            Part uploadFile = request.getPart("file");
            String submittedFileName = uploadFile.getSubmittedFileName();
            uploadFile.write(upload+new Date().getTime()+submittedFileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
        request.setAttribute("msg","上传成功");
        return "forward:/pages/success.jsp";
    }
}

编写上传成功的页面:

<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>success</h1>
${msg}
</form>
</body>
</html>

web层添加文件上传配置【添加在中央处理器加载的servlet】

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springwebmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <multipart-config>
        <max-file-size>20480</max-file-size>
        <!--文件大小阈值,当大于这个阈值时将写入到磁盘,否则在内存中。默认值为0-->
        <file-size-threshold>1048576</file-size-threshold>
    </multipart-config>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

上面的<multipart-config>相当于在mvc.xml里面配置了:

<!--文件上传解析器 id固定为multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

配置mvc:

<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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.java.controller"/>
    <!--开启mvc注解驱动-->
    <mvc:annotation-driven/>
    <!--配置静态资源访问处理器-->
    <mvc:default-servlet-handler/>
    <!--视图解析器-->
    <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>-->
</beans>
posted @ 2023-03-06 14:39  Liku007  阅读(12)  评论(0编辑  收藏  举报