【问题标题】:How to upload a file using Ajax in Scalajs如何在 Scalajs 中使用 Ajax 上传文件
【发布时间】:2017-11-05 13:14:23
【问题描述】:

我正在通过构建图像共享网络应用程序来学习 Scalajs。 在一个表单中,我有一个经典的文件输入标签,我想使用 Ajax 和 jQuery 通过 HTTP Post 请求将它上传到远程服务器。

这是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)
          }
        }
    }
  }
})

任何帮助将不胜感激

【问题讨论】:

    标签: javascript jquery ajax scala scala.js


    【解决方案1】:

    请参阅 Scalajs Showcase Ajax example 以在 scalajs 中执行 post 方法。

    扩展上面的例子,可以写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方法。

    【讨论】:

      【解决方案2】:

      我使用了 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)
                }
              }
          }
        }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        • 2015-08-08
        • 2015-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多