使用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.在全局配置文件中引入相关配置
    <!--multipart处理类-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="4096"/>
    </bean>3, 153, 153);">1
  • 2
  • 3
  • 4
  • 5
    • 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接收文件
    @RequestMapping("upload.ajax")
        @ResponseBody
        public String upload(MultipartFile avatar){
            //处理avatar逻辑
            return "success";
        }
      
      
     
     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    后语

    • 该实现并不难,主要了解表单提交格式和相关实现即可。希望可以帮到相关人员。


    免责声明!

    本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



     
    粤ICP备18138465号  © 2018-2025 CODEPRJ.COM