Javascript 如何在Scalajs中使用Ajax上传文件

Javascript 如何在Scalajs中使用Ajax上传文件,javascript,jquery,ajax,scala,scala.js,Javascript,Jquery,Ajax,Scala,Scala.js,我正在通过构建一个图像共享网络应用程序来学习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-con

我正在通过构建一个图像共享网络应用程序来学习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)
          }
        }
    }
  }
})
lazy val submitement=jQuery(“postButton”)
jQuery(()=>{
submitement.click{
(:JQueryEvent)=>{
dom.ext.Ajax.post(
url=[服务器url],
数据=???,/“应用程序/json”)
).foreach{xhr=>
如果(xhr.status==200){
val x=JSON.parse(xhr.responseText)
println(x)
}
}
}
}
})

非常感谢您的帮助

我使用了FormData Api。它是在为scalajs使用libs

请参阅在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方法

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