formData上傳檔案,

來源:互聯網
上載者:User

formData上傳檔案,

form表單提交的方式上傳檔案:

<form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data">       <h1 >測試通過Rest介面上傳檔案 </h1>       <p >指定檔案名稱: <input type ="text" name="filename" /></p>       <p >上傳檔案: <input type ="file" name="file" /></p>       <p >關鍵字1: <input type ="text" name="keyword" /></p>       <p >關鍵字2: <input type ="text" name="keyword" /></p>       <p >關鍵字3: <input type ="text" name="keyword" /></p>       <input type ="submit" value="上傳"/>  </form>  
不過需要頁面跳轉


Ajax的方式進行請求的:

$.ajax({       url : "http://localhost:8080/STS/rest/user",       type : "POST",       data : $( '#postForm').serialize(),       success : function(data) {            $( '#serverResponse').html(data);       },       error : function(data) {            $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);       }  });  

如上,通過$('#postForm').serialize()可以對form表單進行序列化,從而將form表單中的所有參數傳遞到服務端。 但是上述方式,只能傳遞一般的參數,上傳檔案的檔案流是無法被序列化並傳遞的。不過如今主流瀏覽器都開始支援一個叫做FormData的對象,有了這個FormData,我們就可以輕鬆地使用Ajax方式進行檔案上傳了。

FormData,這裡使用JQuery

Html代碼

<form id= "uploadForm">        <p >指定檔案名稱: <input type="text" name="filename" value= ""/></p >        <p >上傳檔案: <input type="file" name="file"/></ p>        <input type="button" value="上傳" onclick="doUpload()" />  </form> 
Js代碼
function doUpload() {       var formData = new FormData($( "#uploadForm" )[0]);       $.ajax({            url: 'http://localhost:8080/cfJAX_RS/rest/file/upload' ,            type: 'POST',            data: formData,            async: false,            cache: false,            contentType: false,            processData: false,            success: function (returndata) {                alert(returndata);            },            error: function (returndata) {                alert(returndata);            }       });  }  


待續。。。

   
0
0
查看評論

相關關鍵詞:
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.