0

我试图实现在 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>文件实际上是空的,我哪里出错了?

4

1 回答 1

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
    });
}
于 2019-03-18T11:11:29.207 回答