zoukankan      html  css  js  c++  java
  • Spring MVC 文件上传简单示例(form、ajax方式 )

    1、Form Upload

      SpringMVC 中,文件的上传是通过 MultipartResolver 实现的,所以要实现上传,只要注册相应的 MultipartResolver 即可。

      MultipartResolver 的实现类有两个:

    1. CommonsMultipartResolver (需要 Apache 的 commons-fileupload 支持,它能在比较旧的 servlet 版本中使用,兼容性好)
    2. StandardServletMultipartResolver (不需要第三方 jar 包支持,它使用 servlet 内置的上传功能,但是只能在 Servlet 3 以上的版本使用

    以 StandardServletMultipartResolver 为例,使用步骤如下。

    首先,在 web.xml 中为 DispatcherServlet 配置 Multipart:

    <servlet>
      <servlet-name>mvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <multipart-config>
          <max-file-size>5242880</max-file-size>        <!-- 上传文件的大小限制,比如下面表示 5 M -->
          <max-request-size>10485760</max-request-size> <!-- 一次表单提交中文件的大小限制,必须下面代表 10 M -->
          <file-size-threshold>0</file-size-threshold>  <!-- 多大的文件会被自动保存到硬盘上。0 代表所有 -->
        </multipart-config>
    </servlet>

     其次,在spring中注册MultipartResolver:

      <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>

    然后就可以使用了。

    前端代码:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>文件上传</title>
    </head>
    <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="filename">
        <input type="submit" value="提交">
    </form>
    </body>
    </html>

    后端代码:

    package com.oukele.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestPart;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.regex.Pattern;
    
    @Controller
    @RequestMapping(path = "/upload")
    public class FileUploadController {
    
        @RequestMapping(path = "",method = RequestMethod.GET)
        public String getPage(){
            return "fileupload";
        }
    
        @PostMapping
        public String fileUpload(@RequestPart("filename")MultipartFile multipartFile, HttpServletRequest request) {
            if( !multipartFile.isEmpty() ){
                //验证文件是否为图片格式 && 文件大小不能超过 5M  1KB = 1024B
                if( multipartFile.getContentType().contains("image/") && multipartFile.getSize() < 1024 * 1024 * 1024 * 5 ){
                    //图片的存储文件夹
                    String save = request.getServletContext().getRealPath("/images");
                    File file = new File(save);
                    if( !file.exists() ){
                        file.mkdirs();
                    }
                    //文件名
                    String fileName =multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().indexOf("."));
                   //上传文件的后缀
                    String zhui = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."),multipartFile.getOriginalFilename().length());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    //生成新的文件名
                    String fileNewName ="upload_"+fileName+"_"+simpleDateFormat.format(new Date())+zhui;
                    try {
                        //将此图片存储到images文件夹中
                        multipartFile.transferTo(new File(save+"\"+fileNewName));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }else{
                    return "";
                }
    
            }
    
            return "redirect:/upload";
        }
    
    
    }

    运行:

    结果:

     以ajax的方式,进行文件上传

    前端代码:

     <form action="#"  method="post" enctype="multipart/form-data">
          宠物图片: <input type="file" name="filename" id="update_pet_img" style=" 70px">
     </form>
     <img style="margin-top: 50px" class="update_img" src="" width="100px" height="100px" alt="未上传图片">

     js脚本

    <script src="${pageContext.request.contextPath}/js/jquery-1.12.3.js"></script>
    <script>
     //修改区域-->,点击选择文件的时候实现自动上传图片。
        $("#update_pet_img").change(function () {
            var form = $(this).closest("form");
            update_file_img(form);
        });
    
        //图片上传
        function update_file_img(file) {
            var formData = new FormData($(file)[0]);
            //ajax请求
            $.ajax({
                type: "post",
                url: "/imgUpload",
                data: formData,
                contentType: false,//告诉客户端不要设置Content-Type 请求头部
                processData: false,//告诉客户端不处理过程数据
                success: function (data) {//完成后的事件
                    $(".update_img").attr("src", data.img_src);//data.img_src得到图片的地址
                },
                error: function (error) {//出现错误时的事件
                    alert("出错啦。");
                }
            });
    
        }
    </script>

     后端代码:(这里只是简单示例,练习可以适当减少)

    package com.oukele.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Controller
    @RequestMapping(path = "/imgUpload")
    public class FileUpload {
    
        /*
         * 宠物图片上传
         * */
        @PostMapping(produces = "application/json;charset=utf-8")
        @ResponseBody
        public String imgUpload(@RequestPart("filename") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response){
            if (multipartFile.isEmpty()) {
                return "{"error":"文件为空,错误格式"}";
            }
            if (!multipartFile.getContentType().contains("image/")) {
                return "{"error":"只允许上传图片的文件"}";
            }
            if (multipartFile.getSize() > 1024 * 1024 * 1024 * 5) {
                return "{"error":"图片大小不能超过5M"}";
            }
            //图片的存储文件夹
            String save = request.getServletContext().getRealPath("/images");
            File file = new File(save);
            if (!file.exists()) {
                file.mkdirs();
            }
            String file1 = createFile(save, multipartFile);
    
            return file1;
        }
        //创建文件夹,格式为以日期文件名 比如 2018112 , 和 新的文件名,格式为 upload_文件名_日期.后缀名
        public String createFile(String path, MultipartFile multipartFile) {
            boolean flag = false;
            String imgpath ="";
            //创建文件夹
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String dataFile = "/" + simpleDateFormat.format(new Date());
            path += dataFile;
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            //文件名
            String fileName = multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().indexOf("."));
            //上传文件的后缀
            String zhui = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."), multipartFile.getOriginalFilename().length());
            //生成新的文件名
            String fileNewName = "upload_" + fileName + "_" + simpleDateFormat.format(new Date()) + zhui;
            try {
                //将此图片存储到对应的文件夹中
                multipartFile.transferTo(new File(path + "/" + fileNewName));
                 imgpath ="/images"+dataFile+"/"+ fileNewName;
                flag = true;
            } catch (Exception e) {
                flag = false;
                e.printStackTrace();
            }
            if( flag ){
                return "{"img_src":""+imgpath+""}";
            }
    
            return "{"error":"出现异常"}";
        }
    }

     演示:

  • 相关阅读:
    为什么电影里的黑客都不屑用鼠标? (转)
    专注做好一件事(转) focus---这个世界上最成功的人,他们在某一领域获得成功之后,可通过经营杠杆进入任何他们想要涉足的领域。而这都得依赖于他们曾极致的专注在做好一件事情上。
    世间万物都是遵循某种类似的规律,谁先把握了这些规律,谁就最早成为了强者。
    走的时候不要太急,有时间要停下来想一想当初为什么而走,这样,才会走的更稳,走的更明白。
    Android笔记: Android版本号
    Android笔记:真机调试无法输出Log 信息的问题
    阿里云服务器试用
    Android笔记:利用InputStream和BufferedReader 进行字节流 字符流处理
    Android笔记:java 中的数组
    Android笔记:C memory copy
  • 原文地址:https://www.cnblogs.com/oukele/p/9895912.html
Copyright © 2011-2022 走看看