Как загрузить файл в asp. net? - PullRequest
0 голосов
/ 17 марта 2020

Я ищу решение о том, как отправить файл с помощью формы в приложение asp. Я пишу в asp. net Framework MVC Razor.

Моя форма:

<div class="container">
    <div class="col-md-2">
        @using (Html.BeginForm("Data", "Admin", FormMethod.Post, new { encrypte = "multipart/form-data"}))
        {
            <div class="form login-form">
                <label for="username" class="text-info">Wczytaj plik:</label>
                <input type="file" name="file" id="file" />
            </div>
            <div id="register-link" class="text-right">
                <input type="submit" class="btn btn-success" value="Importuj" />
            </div>
            @ViewBag.Message
        }
    </div>
</div>

Мой контроллер:


        [HttpPost]
        public ViewResult Data(HttpPostedFile file = null)
        {
            if(file != null && file.ContentLength > 0)
            {
                string path = Path.Combine(Server.MapPath("~/Upload/Data"), Path.GetFileName(file.FileName));
                file.SaveAs(path);
                ViewBag.Message = "Succes";
            }

            return View("AdminDataView", students);
        }

К сожалению, вышеприведенный код не работает, я что-то не так делаю, есть ли другой способ загрузить файл на asp?

Ответы [ 2 ]

0 голосов
/ 18 марта 2020

Пожалуйста, обратитесь по ссылке ниже, это даст вам лучшее понимание.

{ ссылка }

Надеюсь, это наверняка поможет вам.

0 голосов
/ 17 марта 2020

Я думаю, что есть опечатка, и я предлагаю вам использовать ActionResult вместо ViewResult.

Разница между ActionResult и ViewResult

опечатка : new { enctype="multipart/form-data"}) не new { encrypte = "multipart/form-data"})

Пример кода:

Вид

@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { 
enctype="multipart/form-data"}))  
{  
    <div>  
        @Html.TextBox("file", "", new {  type= "file"}) <br />  
        <input type="submit" value="Upload" />  
        @ViewBag.Message  
    </div>     
}

Контроллер

    [HttpPost]  
    publicActionResultUploadFile(HttpPostedFileBase file)  
    {  
        try  
        {  
            if (file.ContentLength > 0)  
            {  
                string _FileName = Path.GetFileName(file.FileName);  
                string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);  
                file.SaveAs(_path);  
            }  
            ViewBag.Message = "File Uploaded Successfully!!";  
            return View();  
        }  
        catch  
        {  
            ViewBag.Message = "File upload failed!!";  
            return View();  
        }  
    } 
...