Asp.Net或WebAPI获取表单数据流(批量文件上传)
//web或webapi获取表单数据流(批量文件上传)
public jsonresult uploadfile()
{
//httppostedfilebase filebase = request.files["filetouploadkeyid"];
httppostedfilebase filebase = request.files[0]; //获取客户端上载的文件的集合
string resulturl = string.empty;//相对文件路径
string errmsg = string.empty;
if (filebase == null || filebase.contentlength == 0)
{
errmsg = "文件为空";
}
else
{
int maxsize = 1024 * 1024 * 4;
if (filebase.inputstream.length > maxsize)
{
errmsg = "文件过大";
}
else
{
try
{
//循环遍历批量上传的文件
for (int i = 0; i < request.files.count; i++)
{
filebase = request.files[i];
var name = system.io.path.getfilename(filebase.filename);
var filename = "/upload/" + datetime.now.tostring("yymmddhhmmssffff") + "." + name.split('.')[1];
var filepath = system.web.httpcontext.current.server.mappath(filename);
filebase.saveas(filepath);//保存文件
resulturl += filename + ";";//拼接文件相对路径
}
}
catch
{
errmsg = "上传失败";
}
}
}
return json(new { errmsg = errmsg, resulturl = resulturl.trim(';') });
}