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

时间:2019-03-18 10:41:23

标签: c# jquery ajax asp.net-mvc iformfile

我试图实现将文件从客户端传递到mvc中的控制器,以便将文件转换为ByteArray,我当时认为这是一个简单的任务,但实际上给了我一些麻烦。到目前为止,我能够正确击中控制器:

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

$(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控制器

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
    }

就像我之前说过的那样,当前我可以打我的控制器,但是问题是 IList<IFormFile> 文件实际上为空,这是我弄错了吗?

1 个答案:

答案 0 :(得分:0)

我希望这会起作用。 我只有一个文件要发送,所以我正在做的是Asp.Net Core 您可以添加条件,例如 Files.Count 或其他所需的条件。

这是我保存文件的代码

[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
    });
}