简体   繁体   English

我如何将我在file1.html(通过javascript的文件选择控件)中选择的文件获取到file2.php中进行处理

[英]How can I get a file I selected in a file select control in file1.html, trough javascript, into file2.php to be processed

The structure looks like this: 结构如下:

<form>
...
some stuff
...
file select
...
some stuff
...
</form>

I need to send the input data from "file select" while not sending "some stuff" and as far as i've tried I couldn't get a form inside another form so that's not an option. 我需要从“文件选择”中发送输入数据,而不要发送“一些东西”,据我所试,我无法在另一个表单中获取表单,因此这不是一种选择。

The way it works is like this: the file select control isn't displayed at first, clicking a button makes it show the control and some other stuff. 它的工作方式是这样的:首先不显示文件选择控件,单击按钮可以显示该控件和其他内容。 I need a button to submit that file to be checked for different things (naming, size, etc) and uploaded to the server, without changing or reloading the rest of the window. 我需要一个按钮来提交该文件,以检查其他内容(命名,大小等)并上传到服务器,而无需更改或重新加载窗口的其余部分。

I could change the layout a bit and get the file select stuff out of the form but the boss doesn't want to change the design of the window and removing the outer-most form will be a lot of work as it's a very complicated part of the web site. 我可以稍稍更改布局并从表单中删除文件选择内容,但老板不想更改窗口的设计,并且删除最外面的表单将是很多工作,因为这是非常复杂的部分该网站。

So, as the question says: Can I do it? 因此,正如问题所言:我可以这样做吗? Can I get the file trough javascript and send it to another php file for processing? 我可以通过JavaScript获取文件并将其发送到另一个php文件进行处理吗?

The most browser compatible way to achieve this is to use a hidden iframe that you submit the form into. 与浏览器最兼容的方法是使用将表单提交到的隐藏iframe For example: 例如:

<iframe name="my_iframe" id="my_iframe" style="display: none;"></iframe>

<form action="/next_step.php" method="post" target="my_iframe" entype="multipart/form-data">
    <input type="file" name="file_upload" />
    <input type="button" id="upload_btn" value="Upload file" />

    <label for="name">Name</label>
    <input type="text" name="name" id="name" />

    <input type="submit" value="Next step" />
</form>

<script type="text/javascript">
    var btn = document.getElementById('upload_btn');
    btn.onclick = function(){
        var form_elem = document.forms[0];
        // direct file uploads through the hidden iframe
        form_elem.action = '/test_file.php';
        form_elem.target = 'my_iframe';

        // submit the form
        form_elem.submit();

        // now reset for next step in the form
        form_elem.action = '/next_step.php';
        form_elem.target = null;
    };
</script>

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

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