使用FormData格式上传图像并预览图片

前言

  • 作项目时,遇到表单中图像须要跟表单一块儿提交,这样会形成后台没办法接收到图片。后面上网调查后,明白表单提交时是默认application/x-www-form-urlencoded格式,只接受键值对。因此如下例子采用FormData格式异步提交表单,由于formData格式能够接收文件格式。

具体流程

  • 1.引入maven
<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
  • 2.在全局配置文件中引入相关配置
3, 153, 153);">1
  • 2
  • 3
  • 4
  • 5
  • <!--multipart处理类--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="4096"/> </bean>
    • 3.定义jsp文件
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <body>
    <h1>使用formData形式上传文件</h1>
        <form id="uploadForm" method="post" action="/upload.ajax" >
            <input type="file" id="avatar" name="avatar" onchange="previewImage('preview',this)" >
            <img id="preview">
            <button id="submit" type="button">提交</button>
        </form>
    </body>
    </html>
    <script src="/media/js/jquery-1.10.1.min.js"></script>
    <script type="text/javascript"> //检验文件格式并预览 function previewImage(preImageId, imageFile) { var pattern = /(\.*.jpg$)|(\.*.png$)|(\.*.jpeg$)|(\.*.gif$)|(\.*.bmp$)/; if (!pattern.test(imageFile.value)) { alert("系统仅支持jpg/jpeg/png/gif/bmp格式的照片!"); imageFile.focus(); $(imageFile).val(""); return false; } else { var path; if (document.all)//IE { imageFile.select(); path = document.selection.createRange().text; } else//FF { path = URL.createObjectURL(imageFile.files[0]); } $('#' + preImageId).attr('src', path); } } $('#submit').on('click',function () { var formData = new FormData($( "#uploadForm" )[0]); console.log(formData); $.ajax({ type: 'POST', url: '/upload.ajax', data: formData, contentType: false, processData: false, success: function (result) { console.log(result); }, }); }); </script>
    • 4.后台采用MultiPartFile接收文件
      
      
      
      
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    @RequestMapping("upload.ajax") @ResponseBody public String upload(MultipartFile avatar){ //处理avatar逻辑 return "success"; }

    后语

    • 该实现并不难,主要了解表单提交格式和相关实现便可。但愿能够帮到相关人员。
    相关文章
    相关标签/搜索