.Net MVC由于文件路径错误而无法上传文件

时间:2019-06-11 20:58:58

标签: javascript asp.net-mvc

我正在学习MVC,并且下面的代码不起作用:

@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("UploadAsync", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="fileUpload btn btn-default">
        <span>Select Files</span><input type="file" id="file" name="selectFiles" class="upload" onchange="DisplayFilesToUpload()" multiple />
    </div>
    <p id="FilesToUpload"></p>
}

<script>
    function DisplayFilesToUpload() {
        var element = document.getElementById("file");
        var html = "";

        html = "<h3>Image(s) to Upload</h3>"
        for (var i = 0; i < element.files.length; i++) {
            html += "<strong>" + (i + 1) + "</strong>. File: ";
            var file = element.files[i];
            if ('name' in file) {html += file.name + " (";}
            if ('size' in file) {html += "size: " + file.size + " bytes)<br>";}
        }
        html += "<div class='fileUpload btn btn-default'><span>Upload</span><input type='submit' class='upload' value='Upload'/></div>"
        document.getElementById("FilesToUpload").innerHTML = html;
    }
</script>

相应的控制器如下所示:

[HttpPost]
        public async Task<ActionResult> UploadAsync()
        {
            try
            {
                HttpFileCollectionBase files = Request.Files;
                int fileCount = files.Count;

                if (fileCount > 0)
                {
                    for (int i = 0; i < fileCount; i++)
                    {
                        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(GetRandomBlobName(files[i].FileName));
                        await blob.UploadFromFileAsync(files[i].FileName, FileMode.Open);
                    }
                }
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                ViewData["trace"] = ex.StackTrace;
                return View("Error");
            }            
        }

每次上传文件时,都会收到以下错误消息:

  

处理您的请求时发生错误:找不到文件   “ C:\ Program Files(x86)\ IIS Express \ some.png”。

如何解决?

2 个答案:

答案 0 :(得分:0)

尝试以下操作:

[HttpPost]
public async Task<ActionResult> UploadAsync(HttpPostedFileBase[] files)
{
    // You can access each file with
    foreach (HttpPostedFileBase file in files)  
    {
    } 
}

答案 1 :(得分:0)

您可以先将文件保存到服务器。

Request.Files[0].SaveAs(@"C:\Intel\new_file_name.png");
await blob.UploadFromFileAsync(@"C:\Intel\new_file_name.png");

或直接上传文件流。

await blob.UploadFromStreamAsync(Request.Files[0].InputStream);