SpringMVC文件上传

SpringMVC和Struts2的区别
共同点:
1.都是web层框架,都是基于MVC模型编写
2.底层都离不开原始ServletAPI
3.处理请求的机制都是一个核心控制器

区别:
1.SpringMVC的入口是Servlet,而Struts2是Filter
2.SpringMVC是基于方法设计的,而Struts2是基于类,Struts2每次执行都会创建一个动作类。所以SpringMVC会稍微比Struts2快些
3.SpringMVC使用更加简洁,同时还支持JSR303,处理ajax请求更方便

搭建SpringMVC工程步骤

最后一步最重要,我踩过多少坑才知道

fix完之后,tomcat服务器就可以跑起来了,不需要敲一行代码,也不需要配置代码

 

下面是正题

效果图

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: wanglei
  Date: 2019/7/27
  Time: 14:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<h3>传统文件上传</h3>

<form action="user/fileupload1" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>

<h3>SpringMVC文件上传</h3>

<form action="user/fileupload2" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>

<h3>跨服务器文件上传</h3>

<form action="user/fileupload3" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>
</body>
</html>

dispatcher-servlet.xml

<?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/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.jinke.controller"/>

    <!--视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--配置文件解析器对象-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/>
    </bean>

    <!--开启SpringMVC框架注解的支持-->
    <mvc:annotation-driven/>
</beans>

UploadController.java

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UploadController {

    /**
     * 跨服务器上传方式
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload3")
    public String fileupload3(MultipartFile upload) throws Exception {
        System.out.println("跨服务器文件上传...");

        //定义上传服务器路径
        String path = "http://localhost:9090/Fileserver/uploads/";

        //上传文件项
        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
        //创建客户端对象
        Client client = Client.create();
        //和图片服务器进行连接
        WebResource webResource = client.resource(path + saveName);
        //上传文件
        webResource.put(upload.getBytes());


        return "success";
    }

    /**
     * SpringMVC上传方式
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload2")
    public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        System.out.println("springmvc文件上传...");
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        //上传文件项
        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
        upload.transferTo(new File(path, saveName));

        return "success";
    }

    /**
     * 传统上传方式
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload1")
    public String fileupload1(HttpServletRequest request) throws Exception {
        System.out.println("文件上传...");
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //解析request对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        //遍历
        for (FileItem item : items) {
            if (item.isFormField()) {
                //普通表单向
            } else {
                //上传文件项
                String filename = item.getName();
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
                item.write(new File(path, saveName));
                //删除临时文件
                item.delete();
            }
        }

        return "success";
    }
}

需要注意的是,如果配置了CommonsMultipartResolver,传统上传方式就走不通了,因为提前过滤掉了

如果从应用服务器上传文件到文件服务器,保存路径要写对

欢迎关注我的微信公众号:安卓圈

posted @ 2019-07-27 19:43  嘉禾世兴  阅读(5916)  评论(1编辑  收藏  举报