C# mvc 上传多个附件

时间:2022-04-05 05:18:28
  <div class="col-xs-12 mcp-list-item" style="margin-top:20px">
<div class="mcp-list-item-title">附件</div>
<input onchange="upload()" id="uploadFile" name="uploadFile" placeholder="多个请按下Ctrl后选取文件" type="file" value="文件选取" multiple="multiple">
</div>
<div class="col-xs-12 mcp-list-item">
<a class="btn btn-success" onclick="btn_upload()"><i class="fa fa-upload"></i>开始上传</a>
</div> //下面这一段代码是用来显示图片容器的
  <div id="imgList">
<img id="fileUrl" style="width: 100px; height: 100px; border-radius: 100px;" />
</div> <div id="fileList"> </div>
 
        //图片上传
function upload() { var f1 = document.getElementById('uploadFile').files;
if (f1.length>0) {
var form = $('#imgList');
for (var i = 0; i < f1.length; i++) { var src1 = window.URL.createObjectURL(f1[i]);
var imgid='fileUrl_'+i;
var oldElement = $('#fileUrl');
var newElement = $(oldElement).clone();
$(oldElement).attr('id', imgid);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
$(oldElement).attr('src', src1);
// $('#' + imgid).src = src1
}
} //var f = document.getElementById('uploadFile').files[0]; //var src = window.URL.createObjectURL(f);
//var filetype = "GIF,JPEG,JPG,PNG,pdf";
//document.getElementById('fileUrl').src = src; //if (f == null || f == "") {
// dialogMsg('请选择文件!', 0);
// return;
//} else if (f != "" && f != undefined && f != null) {
// var imgtype = ff.toLowerCase().split('.');
// if (filetype.indexOf(imgtype[1].toUpperCase()) == -1) {
// dialogMsg('图片类型必须是.gif,jpeg,jpg,png,pdf中的一种!', 0);
// return;
// }
//} }
function btn_upload() { var refids = [];
var rows = $('#Delivery_Grid').datagrid('getRows');
$.each(rows, function (index, item) {
refids.push(item.reforderid); }); var numArr = [];
var txt = $("#fileList").find("input:file"); //获取所有上传附件框
for (var i = 0; i < txt.length; i++) {
numArr.push(txt.eq(i).attr('id')); //将附件框的ID添加到数组中
} if (!$('#formState').Validform()) {
return false;
}
var postData = $("#formState").GetWebControls(); $.ajaxFileUpload({
url: "/TMS.Service/ServiceMilestone/UploadFile?reforderid=" + refids.join(','),
secureuri: false,
fileElementId: 'uploadFile',
dataType: 'json',
//data: postData,
success: function (data) {
if (data.status) {
dialogMsg(data.message, 1); document.getElementById('fileUrl').src = "";
document.getElementById('uploadFile').src = ""; } else {
dialogMsg(data.msg, 0);
}
}
}); }

记得引入   <script src="~/Content/scripts/uploadify/ajaxfileupload.js"></script>

后台代码:

  [HttpPost]
public ActionResult UploadFile(MilestoneInfo minfo)
{ try
{ var filelist = new List<Cargo.Entity.FileInfoEntity>();
if (minfo == null)
{
throw new Exception("找不到milestone节点所属的业务信息 ");
} if (Request != null && Request.Files != null && Request.Files.Count > )
{
string FileServerUrl = ConfigurationManager.AppSettings["FileServerUrl"].ToString();
string serverBasePath = AppDomain.CurrentDomain.BaseDirectory + @"Upload\temp\";
DirectoryInfo dir = new DirectoryInfo(serverBasePath);
if (!dir.Exists)
{
dir.Create();
}
foreach (string fileStr in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileStr] as HttpPostedFileBase;
if (file != null && file.ContentLength > )
{
string filename = Path.GetFileName(file.FileName);
string savePath = serverBasePath + @"\" + filename;
var fileExtName = Path.GetExtension(savePath);
file.SaveAs(savePath);
string uploadDate = DateTime.Now.ToString("yyyyMMdd");
string address = FileServerUrl + $"Home/UploadFile?module={TMS_Enum.TMS_SysFileInfoEnum.TMS_module.ToString()}&folderId={TMS_Enum.TMS_SysFileInfoEnum.TMS_folderId.ToString()}&uploadDate=" + uploadDate;
var buffer = new WebClient().UploadFile(address, "post", savePath);
string result = Encoding.UTF8.GetString(buffer); var serverFilePath = FileServerUrl + result.Replace("~/", ""); //最终服务器存储的地址
//判断文件是不是存在 清空临时存储的文件
if (System.IO.File.Exists(savePath))
{
//如果存在则删除
System.IO.File.Delete(savePath);
}
filelist.Add(new Cargo.Entity.FileInfoEntity
{
FileExtensions = fileExtName,
FilePath = serverFilePath,
FileName = filename, });
}
} } //这里为了避免上传文件事务长时间锁死,所以放置到这里进行操作,先上传耗时的文件操作,再考虑操作数据库
SaveMilestone(
minfo,
filelist);
return new ResponseModel { status = true, msg = "提交成功!" }; }
catch (Exception ex)
{ return new ResponseModel { status = false, msg = ex.Message };
} }

C# mvc 上传多个附件


C# mvc 上传多个附件

C# mvc 上传多个附件