c# 后台接收formdata对象 enctype="multipart/form-data"提交
问题描述:
这是一个文件上传功能。
c#后台如何接收<input name="upload"
我需要获取这个控件选择的文件的路径
前端
<form id="form1" enctype="multipart/form-data" >
<div>
<input name="upLoad" type="file" id="upLoad" />
<button id="btnUpLoad">上传</button>
<button id="btnDownLoad" >下载</button>
</div>
</form>
js
$(document).ready(function () {
$("#btnUpLoad").click(function () {
$.ajax({
url: "Handler3.ashx",
type: "POST",
data: new FormData($("#form1")[0]),
cache: false,
processData: false,
contentType: false,
success: function () {
},
error: function () {
}
});
return false;
})
})
答
不要用jquery.ajax,不支持传递FormData对象,使用jquery.form.js这个插件,会自动帮你传送文件
http://plugins.jquery.com/form/
或者直接用XMLHttpRequest发送FormData对象:html5 ajax上传文件asp.net示例
获取数据和普通表单提交的一样
答
//上传文件地址
string URLAddress = upLoad2.FileName;
//上传文件存放位置
string receivePath = context.Server.MapPath("~/");
//从上传地址创建一个可读流
Stream str = client.OpenRead(URLAddress);
//实例化以特定编码读取文件的读取器
StreamReader reader = new StreamReader(str);
while (allmybyte > 0)
{
//m:读入缓冲区的总字节数
//从当前流的startmbyte位置,欲读取allmybyte字节,放入byte数组
int m = str.Read(mbyte, startmbyte, allmybyte);
if (m == 0)
break;
//读取起始位置加m
startmbyte += m;
//要读取的字节数减少m
allmybyte -= m;
}
//释放流读取器资源
reader.Dispose();
//释放流资源
str.Dispose();
//文件上传下来存放的路径
string path = receivePath + System.IO.Path.GetFileName(URLAddress);
//实例化文件操作类。设置文件的路径,打开方式,读写权限
FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
//往文件流里写入字节
fstr.Write(mbyte, 0, startmbyte);
//清除此流的缓冲区,使得所有缓冲的数据都写入到文件中
fstr.Flush();
//关闭当前流并释放与之关联的所有资源
fstr.Close();
答
HttpPostedFile upLoad2 = context.Request.Files["upLoad"];
//文件操作类型,上传还是下载
string title = context.Request.Form["title"];
HttpPostedFile upFile = HttpContext.Current.Request.Files["upLoad"];
//提供用于将数据发送到和接收来自通过 URI 确认的资源数据的常用方法
WebClient client = new WebClient();
//分配10000000字节给mbyte
byte[] mbyte = new byte[1000000];
//数组长度
int allmybyte = (int)mbyte.Length;
int startmbyte = 0;