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