简体   繁体   English

使用ajax和formData上传文件

[英]Upload file with ajax and formData

I'm trying to upload a video to the Dailymotion API with ajax. 我正在尝试使用ajax将视频上传到Dailymotion API。

In my script i have : 在我的脚本中,我有:

                //upload the video and get the url
                var xhr =  new XMLHttpRequest();
                xhr.open('POST', upload_url, true);
                var formData = new FormData(document.getElementById("myForm"));
                xhr.send(formData);

My script is working but i have a problem, how can I specify which file field i want to use ? 我的脚本可以运行,但是我有问题,如何指定要使用的文件字段?

If you see var formData = new FormData(document.getElementById("myForm")); 如果看到var formData = new FormData(document.getElementById("myForm")); , myForm is the entire form, if my file input has id="myInput" , how can i specify that ? myForm是整个表单,如果我的文件输入具有id="myInput" ,我该如何指定呢?

I don't want to send all my form, but just one specific field. 我不想发送我的所有表格,而只发送一个特定字段。

Thanks ! 谢谢 !

This do what i want : 这是我想要的:

var file = document.getElementById("myInput").files[0];
var formData = new FormData();
formData.append('file', file);

Create en empty FormData and add the file value to it manually: 创建一个空的FormData并手动将文件值添加到其中:

var file = document.getElementById("myInput").value;
var formData = new FormData();
formData.append('file', file);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM