我正在通过构建图像共享网络应用程序来学习 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)
}
}
}
}
})
任何帮助将不胜感激
最佳答案
引用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方法。
关于javascript - 如何在 Scalajs 中使用 Ajax 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357501/