【问题标题】:Using HTML file type in JavaScript [duplicate]在 JavaScript 中使用 HTML 文件类型 [重复]
【发布时间】:2014-05-16 15:47:12
【问题描述】:

有谁知道如何在 javascript 中管理 <input type="file" id="myFile" /> 以便我可以将文件发送到 php 代码?

我有这样的事情:

<input type="file" id="myFile" />
<input type="button" value="FILE" onclick="useFile()" />

然后,在 javascript 中,我想使用用户上传的文件,因为我想在 PHP 代码中使用它。

如何获取文件并将其作为参数发送到 php?

function useFile() {
   var myFile = document.getElementById("myFile"); //Does this work?
   // then how do I send it to a php?
}

我希望有人可以帮助我。

非常感谢。

【问题讨论】:

  • @putvande 谢谢。不使用 jQuery 是否可以做到这一点?
  • 任何你可以用 jQuery 做的事情,你都可以用 JavaScript 做,但是需要更多的工作。
  • 你不能直接用 PHP 做吗?将其放入表单并将action 设置为PHP 脚本。如果您想事先验证,我可以回答,但这种方法对我来说似乎有点奇怪。
  • 恕我直言,使用 jQuery 比普通的 'ole JavaScript 需要更多的工作。在您问题的代码中,myFile 将有一个 files 属性,其中包含 File 对象的 FileList(伪数组)。只需将 append 单个文件添加到 FormData 对象和 xhr.send() 到 FormData 对象。
  • 这个问题回答了你的问题:stackoverflow.com/questions/7138989/…

标签: javascript php html file


【解决方案1】:

你能提交表格吗?如果是这样,那就很简单了。这是 HTML:

<form method="post" action="myScript.php"> <!-- Make a form tag that sends the input (using post) to your PHP script -->
    <input type="file" id="myFile" />  <!-- As you had above -->
    <input type="submit"/>  <!-- create a submit button that, when clicked, will send the file to the server and redirect the page to myScript.php -->
</form>

如果您不确定帖子是什么,请查看此网站:http://www.restapitutorial.com/ 并阅读此文档:http://www.mediafire.com/view/6hmhaygp099gfdh/RESTful_Best_Practices-v1_1.pdf。

但是,如果您无法提交表单,您可以通过在 JavaScript 中注册 onchange 处理程序来获取文件。查看此答案以获取更多信息:how to get files from <input type='file' .../> (Indirect) with javascript。

您的项目中有 JQuery 吗?它可以很容易地通过 POST 将文件发送到您的服务器。在此处阅读更多信息:http://api.jquery.com/jquery.post/。

如果您没有 JQuery,您可以使用 XMLHTTPRequest 发送帖子。这个页面有一些关于如何做的很好的信息:http://www.openjs.com/articles/ajax_xmlhttp_using_post.php,这里是 XMLHTTPRequest 的文档:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 2014-07-24
    • 2017-01-02
    • 2012-10-31
    • 2020-12-13
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多