将文件附加到输入type ="file".用JavaScript [英] Attach file to input type="file" with javascript

查看:88
本文介绍了将文件附加到输入type ="file".用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将JavaScript生成的文件(最多几MB)发送到服务器.我需要使用POST(而不是ajax POST)来完成此操作.

I need to send file (up to few MB) generated by JavaScript to server. I need to do it with POST (not ajax POST).

如何通过JavaScript将文件添加到输入type ="file"?根据预填充HTML表单文件输入,看来这是不可能的由于安全原因.但是我在浏览器中创建了文件,这不应该是安全问题.

How can I add file to input type="file" by JavaScript? According to Pre-Populate HTML form file input it seems that it is not possible due to security reasons. But I create the file in browser, this should not be the security issue.

我可能可以将文件作为文本粘贴到其他类型的输入中.但是我不认为这是正确的.

I can probably paste the file as text to other type of input. But I do not feel that it is correct.

这里的解决方案是什么?有没有办法将文件从浏览器放置到文件输入中?还是可以与其他输入一起使用?有没有办法在没有输入元素的情况下将文件打包到POST?

What is solution here? Is there way how to put file from browser to file input? Or is it ok to do it with other input? Is there a way how to pack the file to POST without input element?

我想用的是什么

$("#button").click(function(e) {
    $('#file').val(export_pdf());
    $('#form').submit();
});

推荐答案

无法创建文件并将其附加到HTML表单输入,但是使用FormData对象,您可以将生成的文件作为一部分发送到服务器帖子请求.

It isn't possible to create a file and attach it to an HTML form input but using the FormData object you could send a generated file to the server as part of a post request.

从MDN中提取:

var formData = new FormData();

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

哪个应该可以使您获得与JS生成的文件发送到服务器的结果相同的结果.

Which should get you the same result of a file generated by JS sent to the server.

这篇关于将文件附加到输入type ="file".用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆