多附件上传

html前台

<form action="/api/Manuscript/AddReviewOpinionFile" method="post" enctype="multipart/form-data">   //这个方法仅限于测试使用
选择图片: <input type="file" name="uploads" multiple >   //multiple  这个属性是在html5中新增一个附件文本框可上传多个附件
<input type="submit">
</form>

注: 在实际开发中应该是异步的form表单提交,而非同步

异步上传:

//方式1$(function ()

{   $('#form2').ajaxForm

({ success: function (responseText) { alert(responseText); } });

});

//这种方式是点击完windows文件框后执行ajax操作

//方式2(通过ajaxSubmit直接执行ajax操作)

$(function ()

{ $(".but2").click(function ()

{ $('#form2').ajaxSubmit({ success: function (responseText) { alert(responseText); } });

}); });

//这种方式是点击提交按钮执行ajax

注: 上述俩中方式需要导入jquery.jsjquery.form.js 俩个jquery包

 //方式3

<input id="fileinfo" type="file" class="notFormFile" />
<button type="button" class="btnNotForm">上传4</button>
//方式4
$(".btnNotForm").click(function () {
    var formData = new FormData();//初始化一个FormData对象
    formData.append("files", $(".notFormFile")[0].files[0]);//将文件塞入FormData
    $.ajax({
        url: "/Home/SaveFile2",
        type: "POST",
        data: formData,
        processData: false,  // 告诉jQuery不要去处理发送的数据
        contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
        success: function (responseText) {
            alert(responseText);
        }
    });
});

// c# 后台   :   这个附件上传是 传到当前解决方案的并集目录下的文件夹, 

if(HttpContext.Current.Request.Files.Count>0)

{

string Audit = "被审计单位文件夹";
string path = HttpContext.Current.Server.MapPath("~/" + Audit + "\");     //获取当前文件夹路径
string[] temp = path.Split("\".ToCharArray());
string LevelPath = "";
for (int i = 0; i < temp.Length - 3; i++)
{
LevelPath += temp[i];
LevelPath += "\";
}
var firstCatalog = LevelPath + Audit;
if (!Directory.Exists(firstCatalog))//如果不存在就创建file文件夹  
{
Directory.CreateDirectory(firstCatalog);
}
if (!Directory.Exists(firstCatalog + "\" + AuditProjectId))//如果不存在就创建file文件夹
{
Directory.CreateDirectory(firstCatalog + "\" + AuditProjectId);
}
var URL = firstCatalog + "\" + AuditProjectId + "\";
Guid identifier = Guid.NewGuid();

 var httpfile = HttpContext.Current.Request.Files[i];   //获取当前文件夹
string suffix = httpfile.FileName.Substring(httpfile.FileName.LastIndexOf('.'));   //获取文件夹后缀
if (httpfile != null)
{
httpfile.SaveAs(URL + identifier + suffix);  //保存文件流

#region 这些为返回值, 不需要择直接忽略
ReviewOpinionFileDTO opmodel = new ReviewOpinionFileDTO();
opmodel.ID = identifier;
opmodel.FileName = httpfile.FileName;
opmodel.FileSize = (httpfile.ContentLength / 1024) + "kb";
opmodel.FileURL = URL + identifier + suffix;
opmodel.FileType = suffix;

#endregion
return opmodel;
}

}

//http://www.cnblogs.com/zhaopei/archive/2017/07/24/upload.html

博主写的非常详细,实用

原文地址:https://www.cnblogs.com/LoveAndPeace/p/7227437.html