我想用jQuery异步上传文件。
$(文档).ready(函数(){$(“#uploadbutton”).click(函数(){var filename=$(“#file”).val();$.ajax美元({类型:“POST”,url:“addFile.do”,enctype:'多部分/表单数据',数据:{文件:文件名},成功:函数(){alert(“上传的数据:”);}});});});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js“></script><span>文件</span><input type=“file”id=“file”name=“file”size=“10”/><input id=“uploadbutton”type=“button”value=“Upload”/>
我只得到文件名,而不是上传文件。我可以做什么来解决这个问题?
您可以使用JavaScript或jQuery进行异步多文件上传,而无需使用任何插件。您还可以在进度控件中显示文件上载的实时进度。我遇到了两个不错的链接-
带有进度条的基于ASP.NET Web表单的多文件上载功能jQuery中基于ASP.NET MVC的多文件上载
服务器端语言是C#,但您可以进行一些修改,使其与其他语言(如PHP)一起使用。
文件上载ASP.NET核心MVC:
在html中的View create file upload控件中:
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
现在在控制器中创建动作方法:
[HttpPost]
public async Task<IActionResult> Add(IFormFile[] mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
hostingEnvironment变量的类型为IHostingEnvironment,可以使用依赖注入将其注入控制器,例如:
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
没有Jquery的现代方法是,当用户选择一个文件时,使用从<input type=“file”>返回的FileList对象,然后使用Fetch发布包裹在FormData对象周围的FileList。
// The input DOM element // <input type="file">
const inputElement = document.querySelector('input[type=file]');
// Listen for a file submit from user
inputElement.addEventListener('change', () => {
const data = new FormData();
data.append('file', inputElement.files[0]);
data.append('imageName', 'flower');
// You can then post it to your server.
// Fetch can accept an object of type FormData on its body
fetch('/uploadImage', {
method: 'POST',
body: data
});
});
使用HTML5和JavaScript,异步上传非常容易,我创建了上传逻辑和html,这不是完全有效的,因为它需要api,但演示了它是如何工作的,如果你有一个名为/upload的端点从你的网站的根目录,这段代码应该适合你:
const asyncFileUpload=()=>{const fileInput=document.getElementById(“文件”);const file=文件输入文件[0];const-uri=“/upload”;const-xhr=新XMLHttpRequest();xhr.upload.onprogress=e=>{常量百分比=e.loaded/e.total;console.log(百分比);};xhr.onreadystatechange=e=>{如果(xhr.readyState==4&&xhr.status==200){console.log(“文件已上载”);}};xhr.open(“POST”,uri,true);xhr.setRequestHeader(“X-FileName”,文件名);xhr.send(文件);}<表单><span>文件</span><input type=“file”id=“file”name=“file”size=“10”/><input onclick=“asyncFileUpload()”id=“upload”type=“button”value=“upload”/></form>
还有一些关于XMLHttpReques的进一步信息:
XMLHttpRequest对象所有现代浏览器都支持XMLHttpRequest对象。XMLHttpRequest对象可用于与web交换数据幕后服务器。这意味着可以更新而不重新加载整个页面。
创建XMLHttpRequest对象所有现代浏览器(Chrome、Firefox、,IE7+、Edge、Safari、Opera)有一个内置的XMLHttpRequest对象。创建XMLHttpRequest对象的语法:variable=new XMLHttpRequest();
跨域访问出于安全原因,现代浏览器不会允许跨域访问。这意味着网页和它试图加载的XML文件,必须位于同一服务器上。W3Schools上的示例都是位于W3Schools中的XML文件领域如果您想在自己的网页上使用上面的示例您加载的XML文件必须位于您自己的服务器上。
有关详细信息,请继续阅读此处。。。
您可以通过JavaScript使用更新的Fetch API。这样地:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
优点:所有现代浏览器都支持Fetch API,因此您不必导入任何内容。此外,请注意,fetch()返回Promise,然后使用.then(..代码处理响应..)异步处理Promise。