2017-06-04 20 views
1

我正在通過構建一個圖像共享Web應用程序來學習Scalajs。 在一個表單中,我有一個經典的文件輸入標籤,並希望通過HTTP Post請求將它使用Ajax和jQuery上傳到遠程服務器。如何使用Scalajs中的Ajax上傳文件

這是HTML:

<input id="postTitle" class="form-control" placeholder="Title" type="text" aria-describedby="basic-addon1"> 

<input id="file" class="form-control" placeholder="Browse" type="file" aria-describedby="basic-addon1"> 

<input id="tags" class="form-control" placeholder="Tags in format ['tag 1', 'tag 2',...]" type="text"> 

<button id="postButton" class="btn btn-success">Submit</button> 

這裏是底層的Scala代碼:

lazy val submitElement = jQuery("#postButton") 
jQuery(() => { 
    submitElement.click { 
    (_: JQueryEvent) => { 
      dom.ext.Ajax.post(
      url = [server_url], 
      data = ???, // <-- How do I get the file? 
      headers = Map("Content-Type" -> "application/json") 
     ).foreach { xhr => 
      if (xhr.status == 200) { 
      val x = JSON.parse(xhr.responseText) 
      println(x) 
      } 
     } 
    } 
    } 
}) 

任何幫助,將不勝感激

回答

0

我用FORMDATA API。它與庫做了scalajs https://github.com/scalajs-io/form-data

lazy val submitElement = jQuery("#postButton") 

jQuery(() => { 
    submitElement.click { 
    (_: JQueryEvent) => { 
     val file_data = jQuery('#file').prop("files")(0); 
     val form_data = FormData();     
      form_data.append('file', file_data); 

      dom.ext.Ajax.post(
      url = [server_url], 
      data = form_data, 
      headers = Map("Content-Type" -> "application/json") 
     ).foreach { xhr => 
      if (xhr.status == 200) { 
      val x = JSON.parse(xhr.responseText) 
      println(x) 
      } 
     } 
    } 
    } 
}) 
1

參考Scalajs Showcase Ajax example在scalajs執行後的方法。

擴展上面的例子,您可以編寫postAsFormData方法,並將上傳的文件作爲formData傳遞。

def postAsFormData(url: String, 
    data: FormData, 
    timeout: Int = 0, 
    headers: Map[String, String] = Map.empty, 
    withCredentials: Boolean = false) = { 
     ajax.post(url, InputData.formdata2ajax(data), timeout,headers, withCredentials, "") 
    } 

傳遞文件輸入作爲

val formData= new FormData() 
formData.append("file",$("#fileInput").prop("files").item(0)) 

,然後調用AJAX postAsFormData方法。