zoukankan      html  css  js  c++  java
  • SpringMvc实现文件上传

    文件上传的前提

    A form 表单的 enctype 取值必须是:multipart/form-data
    (默认值是:application/x-www-form-urlencoded)
    enctype:是表单请求正文的类型
    B method 属性取值必须是 Post
    C 提供一个文件选择域<input type=”file” />

    文件上传的原理分析

    当 form 表单的 enctype 取值不是默认值后,request.getParameter()将失效。 enctype=”application/x-www-form-urlencoded”时,form 表单的正文内容是:
    key=value&key=value&key=value
    当 form 表单的 enctype 取值为 Mutilpart/form-data 时,请求正文内容就变成:
    每一部分都是 MIME 类型描述的正文
    -----------------------------7de1a433602ac 分界符
    Content-Disposition: form-data; name="userName" 协议头
    aaa 协议的正文
    -----------------------------7de1a433602ac
    Content-Disposition: form-data; name="file"; 
    filename="C:UserszhyDesktopfileupload_demofile.txt"
    Content-Type: text/plain 协议的类型(MIME 类型)
    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    -----------------------------7de1a433602ac--
    

    借助第三方组件实现文件上传

    使用 Commons-fileupload 组件实现文件上传,需要导入该组件相应的支撑 jar 包:Commons-fileupload 和
    commons-io。commons-io 不属于文件上传组件的开发 jar 文件,但Commons-fileupload 组件从 1.1 版本开始,它
    工作时需要 commons-io 包的支持。

    普通文件上传

    拷贝jar包

    编写 jsp 页面

    <%--//传统上传方式--%>
        <form action="/user/hello" method="post" enctype="multipart/form-data">
            <input type="file" name="upload" id="file" value="上传文件">
            <input type="submit" value="上传">
        </form>
    

    编写控制器

     @RequestMapping(path = "/hello",headers = "User-Agent")
    //    返回值为void
        public String saveFile(HttpServletRequest request,HttpServletResponse response) throws Exception {
            request.setCharacterEncoding("UTF-8");
    //        String path = request.getSession().getServletContext().getRealPath("");
    //        System.out.println();
            String path="D:\桌面\201";
            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 name = item.getName();
                    //完成文件上传
                    long time = new Date().getTime();
                    name=time+name;
                    item.write(new File(file,name));
                    //删除临时文件
                    item.delete();
                }
            }
            return "ok";
        }
    

    SpringMvc中的文件上传

    配置jsp文件

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

    编写控制器

    @RequestMapping("/test05")
        public String test05(HttpServletRequest request,MultipartFile upload,HttpServletResponse response) throws IOException {
            request.setCharacterEncoding("UTF-8");
    //        String path = request.getSession().getServletContext().getRealPath("");
    //        System.out.println();
            String path="D:\桌面\201";
            File file=new File(path);
            if (!file.exists()){
                file.mkdirs();
    
            }
            //获取文件名
            String name=upload.getOriginalFilename();
            long time = new Date().getTime();
            name=time+name;
            //传入指定路径
            upload.transferTo(new File(path,name));
    
            return "ok";
        }
    

    配置文件解析器

    <!-- 配置文件上传解析器 --> <bean id="multipartResolver" <!-- id 的值是固定的-->
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置上传文件的最大尺寸为 5MB --> <property name="maxUploadSize"> <value>5242880</value>
    </property>
    </bean>
    注意:
    文件上传的解析器 id 是固定的,不能起别的名称,否则无法实现请求参数的绑定。(不光是文件,其他
    字段也将无法绑定)
    

    springmvc 跨服务器方式的文件上传

    分服务器的目的

    在实际开发中,我们会有很多处理不同功能的服务器。例如:
    应用服务器:负责部署我们的应用
    数据库服务器:运行我们的数据库
    缓存和消息服务器:负责处理大并发访问的缓存和消息
    文件服务器:负责存储用户上传文件的服务器。
    (注意:此处说的不是服务器集群
    

    分服务器处理的目的是让服务器各司其职,从而提高我们项目的运行效率。

    准备两个 tomcat 服务器,并创建一个用于存放图片的 web 工程

    在文件服务器的 tomcat 配置中加入,允许读写操作。文件位置:


    加入此行的含义是:接收文件的目标服务器可以支持写入操作。

    拷贝 jar 包

    在我们负责处理文件上传的项目中拷贝文件上传的必备 jar 包

    编写控制器实现上传

    注意:打包时 war包 和 war exploded 是不一样的 文件路径不一样 一般导war exploded

     /**
         * 夸服务器上传文件
         * @param upload
         * @param response
         * @return
         * @throws IOException
         */
        @RequestMapping("/test06")
        public String test05(MultipartFile upload,HttpServletResponse response) throws IOException {
            //书写服务器地址和位置
           String path="http://localhost:8080/uploads/"; 
            File file=new File(path);
            if (!file.exists()){
                file.mkdirs();
    
            }
            //获取文件名
            String name=upload.getOriginalFilename();
            System.out.println(name);
            long time = new Date().getTime();
            name=time+name;
            //获取服务器客户端
            Client client = Client.create();
            //和图片服务器进行连接
            WebResource resource = client.resource(path + name);
            System.out.println(resource);
            //上传文件字节流
            resource.put(upload.getBytes());
    
            return "ok";
        }
    
    
  • 相关阅读:
    Java设计模式之单例模式
    docker常用命令2
    Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate';
    Apache RocketMQ在linux上的常用命令
    RocketMQ的broker启动失败解决
    xshell与xftp使用注意
    Springboot项目打包成jar运行2种方式
    docker常用命令记录
    MySql常用语句总结更新
    springboot启动报错start bean 'eurekaAutoServiceRegistration' NullPointerException
  • 原文地址:https://www.cnblogs.com/zgrey/p/13409523.html
Copyright © 2011-2022 走看看