jQuery上传文件和Core Web API接收保存文件

jQuery上传文件和API接收保存文件
- jQuery代码是:

        
        

        $("#upload").click(function (evt) {
            var fileUpload = $("#files").get(0);
            var files = fileUpload.files;
            var data = new FormData();
            console.log("length=" + files.length);
            for (var i = 0; i < files.length ; i++) {
                data.append(files[i].name, files[i]);
            }
            data.append("1111", "222");
            $.ajax({
                type: "POST",
                url: "http://localhost:50090/api/test",
                contentType:false,
                dateType:"json",
                processData: false,
                data: data,
                success: function (json) {
                    alert(json);
                    var list = JSON.parse(json);
                    alert(list.res);
                },
                error: function () {
                    alert("There was error uploading files!");
                }
            });
        });
  • API代码是:

        string path = "";
        long size = 0;
        int i = 0;
        var files = HttpContext.Request.Form.Files;
        if (files.Count > 0)
        {
            //可以写遍历files
            var file = files[0];
            string upload_path = Directory.GetCurrentDirectory() + "/wwwroot";
            DateTime now = DateTime.Now;
            if (Directory.Exists(upload_path + "/images/" + now.Year) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(upload_path + "/images/" + now.Year);
            }
            if (Directory.Exists(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd")) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd"));
            }
            upload_path = upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd");//新的目录
    
            var filename = ContentDispositionHeaderValue
                            .Parse(file.ContentDisposition)
                            .FileName
                            .Trim('"');
            string houzhui = filename.Substring(filename.IndexOf("."));
            var filenamenew = DateTime.Now.ToString("yyyyMMddHHmmssfff") + houzhui;
            filename = upload_path+"/" + filenamenew;
            path= "/images/" + now.Year + "/" + now.ToString("MMdd")+"/"+ filenamenew;
            size += file.Length;
            using (FileStream fs = System.IO.File.Create(filename))
            {
                file.CopyTo(fs);
                fs.Flush();
                i += 1;
            }
        }
    
    • 参考文档:
      1. http://www.binaryintellect.net/articles/f1cee257-378a-42c1-9f2f-075a3aed1d98.aspx
      1. https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads

你可能感兴趣的:(jQuery上传文件和Core Web API接收保存文件)