<input type="file" id="avatar" name="avatar"> <button type="button">保存</button>
('button').click(function(){ var files = $('#avatar').prop('files'); //多个 //或者 var files = $('#avatar')[0].files[0] //单个 var data = new FormData(); data.append('avatar', files[0]); $.ajax({ url: '/api/upload', type: 'POST', data: data, cache: false, processData: false, contentType: false }); });
或
<input type="file" id="input_upload_file" onchange="uploadFun(event)" accept=".xls, .xlsx" style="display:none;" /> <button id="btn_upload_file" class="btn btn-success btn-sm"> <i class="fa fa-file-excel-o" aria-hidden="true"></i> 上传excel </button>
$('#btn_upload_file').click(function () { $('#input_upload_file').click(); }); var uploadFun = function (evt) { var files = evt.target.files; var file = files[0]; console.log(file == null ? "" : file.name); var data = new FormData(); data.append('excel', files[0]); $.ajax({ url: '/api/upload', type: 'POST', data: data, cache: false, processData: false, contentType: false, success: (result) => { if (result) tableData.ajax.reload(); else alert("出错了,请联系管理员"); } }); }
服务端
public string UploadExcel([FromForm] IFormCollection formCollection) { String result = "Fail"; if (formCollection.ContainsKey("user")) { var user = formCollection["user"]; } FormFileCollection fileCollection = (FormFileCollection)formCollection.Files; foreach (IFormFile file in fileCollection) { StreamReader reader = new StreamReader(file.OpenReadStream()); String content = reader.ReadToEnd(); String name = file.FileName; String filename = @"D:/Test/" + name; if (System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } using (FileStream fs = System.IO.File.Create(filename)) { // 复制文件 file.CopyTo(fs); // 清空缓冲区数据 fs.Flush(); } result = "Success"; } return result; }
或
/// <summary> /// 事件上传 /// </summary> /// <param name="file">文件信息</param> /// <param name="Id">Id</param> /// <returns></returns> [HttpPost] [DisableRequestSizeLimit] public async Task<IActionResult> EventUpload(IFormFile file, int Id) { if (file == null) { return Ok(new { code="201",msg= "请上传文件" }); } var fileExtension = Path.GetExtension(file.FileName); if (fileExtension == null) { return Ok(new { code = "201", msg = "文件无后缀信息" }); } long length = file.Length; if (length > 1024 * 1024 * 300) //200M { return Ok(new { code = "201", msg = "上传文件不能超过300M" }); } string Paths = Path.GetFullPath(".."); string guid = Guid.NewGuid().ToString(); string stringPath = Paths + $"BufFile\\OutFiles\\DownLoadFiles\\Video\\{guid}\\"; string filePath = $"{stringPath}"; if (!System.IO.Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } var saveName = filePath + file.FileName; using (FileStream fs = System.IO.File.Create(saveName)) { await file.CopyToAsync(fs); fs.Flush(); } return Ok(new { code = "201", msg = "上传成功" }); }
标签:files,core,false,data,file,var,new,net,上传 From: https://www.cnblogs.com/fireicesion/p/16738715.html