使用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