html - asp.net ajax 上传文件总是为空
问题描述
我正在尝试使用 jquery ajax 上传文件,我可以看到文件对象、它的名称、它的大小等。
在控制台中formdata.get("files")
,但context.request.files
大小始终为零,似乎服务器没有收到来自客户端的文件,HttpPostedFileBase
请求始终为空。
如何解决?
HTML:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadKpData.aspx.cs" Inherits="WebApp.Admin.UploadKpData" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="./../Scripts/jquery-1.4.4.min.js"></script>
</head>
<body>
<div>
<div>
<input type="file" id="kpData"/>
<button type="submit" id="uploadKp" />
</div>
</div>
</body>
<script>
$("#uploadKp").click(function () {
var formdata = new FormData();
var files = $("#kpData").get(0).files[0];
formdata.append("files", files);
$.ajax({
url: "../../ds/UploadExcel.ashx",
type: "POST",
async: false,
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formdata,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
})
</script>
</html>
上传Excel.ashx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApp.ds
{
public class UploadExcel : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpFileCollection file = context.Request.Files;
HttpPostedFile file1 = file[0];
string fileName = context.Server.MapPath("~/tmp/" + "test2.xlsx");
file1.SaveAs(fileName);
context.Response.ContentType = "text/plain";
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
解决方案
我检查了你的代码,一切都在为我工作。
让我分享一些截图:
处理程序获取文件:
项目结构:
HTML页面:
推荐阅读
- mysql - 如何在 MySQL 中创建一个出现计数器,每次计数器发现它出现的 id 都会增加?
- karate - 通过空手道 DSL 中的示例关键字的动态有效负载
- python-3.x - 当特定列值对于某些行数连续时如何获取行
- semantic-versioning - 当项目各部分之间的兼容性不同时如何使用语义版本控制
- uitableview - 如何分配“字符串”类型的值?输入“UIImage?”
- three.js - 为什么我的遮挡剔除在 Three.js 中失败?
- nginx - 如何使 nixos 上的 grafana 在本地网络中可用
- javascript - Discord.js 提醒命令 TypeError: Expected a number
- html - html 中 Angular 的反应式表单控件的语法
- python - 使用 Heroku 部署 Streamlit 应用程序时出现问题