简体   繁体   English

MVC通过$ .ajax将文件传递给控制器

[英]MVC passing a file to a controller via $.ajax

I'm trying to achieve to pass a file from the client to my controller in mvc in order to transform the file to a ByteArray, I was thinking that was a simple task but it actually giving me some hard times.. so far I'm able to hit correctly my controller: 我试图实现将文件从客户端传递到mvc中的控制器,以便将文件转换为ByteArray,我当时认为这是一个简单的任务,但实际上给了我一些麻烦。能够正确命中我的控制器:

HTML 的HTML

<form method="post" id="myform" enctype="multipart/form-data"
              asp-controller="UploadFiles" asp-action="Index">
            <div class="form-group">
                <div class="col-md-10">
                    <p>Seleziona un file ORI ed un file MOD.</p>
                    <label for="fileOri">Seleziona ORI</label>
                    <input id="fileOri" type="file" name="fileOri" multiple />
                    <p></p>
                    <label for="fileMod">Seleziona MOD</label>
                    <input id="fileMod" type="file" name="fileMod" multiple />
                    <p></p>
                    <input id="check" name="checkBoxCorreggi" type="checkbox" />
                    <label for="check">Correggi Checksum</label>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-10">
                    <p></p>
                    <input type="submit" id="VerificaChecksum" value="Verifica Checksum" />
                    <!--value= "Verifica Checksum-->
                    <p></p>
                </div>
            </div>
        </form>

JavaScript 的JavaScript

$(function () {
    $('#VerificaChecksum').click(function () {

        var file = document.getElementById('fileOri'),
            formData = new FormData();
        if (file.files.length > 0) {
            for (var i = 0; i < file.files.length; i++) {
                formData.append('file' + i, file.files[i]);
            }
        }

        $.ajax({
            url: '@Url.Action("UploadFiles", "UploadFiles")',
            type: 'POST',
            data: formData,
            dataType: "json",
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

MVC CONTROLLER MVC控制器

public class UploadFilesController : Controller
    {
        int result = 0;
        int count = 0;
        byte[] fileOri;
        byte[] fileMod;

        [DllImport(@"c:\Windows\System32\inetsrv\dll194.dll", EntryPoint = "get_cks_XXX")]
        public static extern int get_cks_XXX(byte[] pBuf_mod, byte[] pBuf_ori, int len_Buf, bool flag);
        private readonly IHostingEnvironment _hostingEnvironment;

        public UploadFilesController(IHostingEnvironment hostingEnvironment)
        {
            this._hostingEnvironment = hostingEnvironment;
        }
        #region snippet1
        [HttpPost("UploadFiles")]
        public async Task<IActionResult> Post(IList<IFormFile> files, string[] checkBoxCorreggi)
        {
            long size = files.Sum(f => f.Length);

            // full path to file in temp location
            var filePath = Path.GetTempFileName();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    using (var stream = new MemoryStream())
                    {
                        await formFile.CopyToAsync(stream);
                        if (count == 0)
                        {
                            fileOri = stream.ToArray();
                        }
                        else
                        {
                            fileMod = stream.ToArray();
                        }

                    }
                }
                count++;
            }
            if (checkBoxCorreggi.Length == 1)
            {
                result = get_cks_XXX(fileMod, fileOri, fileOri.Length, true);
                return File(fileMod, "application/force-download", "modCorretto.mod");
            }
            else
            {
                result = get_cks_XXX(fileMod, fileOri, fileOri.Length, false);
                return Ok(new { count = files.Count, size, filePath });
            }
        }
        #endregion
    }

As I said before I'm currently able to hit my controller, but the problem is that the IList<IFormFile> files is actually null, where I'm getting wrong? 就像我之前说过的那样,当前我可以打我的控制器,但是问题是IList<IFormFile>文件实际上是空的,我在哪里弄错了?

I hope this will work. 我希望这会起作用。 I have just only one file to send so i am doing this is Asp.Net Core You can add your conditions as well like Files.Count or something you want. 我只有一个要发送的文件,所以我正在做的就是Asp.Net Core您可以添加条件,例如Files.Count或您想要的东西。

Here is my code to save file 这是我保存文件的代码

[HttpPost]
public async Task<JsonResult> SaveRegistration(string registration)
{
    var message = "";
    var status = "";
    try
    {
        var path = Path.Combine(_hostingEnvironment.WebRootPath, "Files\\Images");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        path += "\\";
        if (!string.IsNullOrEmpty(registration))
        {

            var reg = new Registration();
            reg.Name = registration;
            var file = Request.Form.Files[0];
            if (file != null)
            {
                var fileName = file.FileName;
                if (System.IO.File.Exists(path + fileName))
                {
                    fileName = $"{DateTime.Now.ToString("ddMMyyyyHHmmssfff")}-{fileName}";
                }
                using (var fileStream = new FileStream(path + fileName, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                reg.Picture = fileName;
            }
            _context.Registration.Add(reg);
            await _context.SaveChangesAsync();

            message = "Data is not saved";
            status = "200";
        }
    }
    catch (Exception ex)
    {
        message = ex.Message;
        status = "500";
    }
    return Json(new
    {
        Message = message,
        Status = status
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM