• net core上传文件


    <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 = "上传成功" });
            }
    

      

  • 相关阅读:
    I Hate It
    hdu 2112 HDU Today ( Dijkstra )
    hdu 1280 前m大的数
    hdu 4252 A Famous City
    hdu 2647 Reward
    hdu 2845 Beans
    hdu 3548 Enumerate the Triangles ( 优 化 )
    hdu 3552 I can do it! (贪心)
    HDU 3033 I love sneakers!(分组背包变形)
    hdu 1712 ACboy needs your help 分组背包
  • 原文地址:https://www.cnblogs.com/fireicesion/p/16738715.html
Copyright © 2020-2023  润新知