загрузка файлов в ASP.NET MVC - PullRequest
       1

загрузка файлов в ASP.NET MVC

0 голосов
/ 24 августа 2010

Когда я выбираю файл и отправляю файл для загрузки, я не могу получить значение пути к файлу в моей модели. В контроллере это отображается как null. Что я делаю не так?

View

<form method="post" action="/Account/Profile" enctype="multipart/form-data">
    <label>Load photo: </label>
    <input type="file" name="filePath" id="file" />
    <input type="submit" value="submit" />
</form>

Контроллер

public ActionResult Profile(ProfileModel model, FormCollection form)
{
    string path = Convert.ToString(model.FilePath);
    return View();
}

Модель

public HttpPostedFileBase FilePath
{
    get
    {
        return _filePath;
    }
    set
    {
        _filePath = value;
    }
}

public bool UploadFile()
{
    if (FilePath != null)
    {
        var filename = Path.GetFileName(FilePath.FileName);
        FilePath.SaveAs(@"C:\" + filename);
        return true;
    }
    return false;
}

Ответы [ 3 ]

2 голосов
/ 24 августа 2010

Я не думаю, что привязка модели работает с HttpPostedFileBase ...

Она должна работать, если вы возьмете ее из своей ViewModel и сделаете так:

public ActionResult Profile(HttpPostedFileBase filePath)
{
    string path = Convert.ToString(filePath);
    return View();
}

HTHs,
Charles

Ps.Этот пост может помочь объяснить: ASP.NET MVC опубликовал привязку модели файла, когда параметром является Модель

0 голосов
/ 22 июня 2017

Вместо использования HttpPostedFileBase я бы использовал IFormFile

public class ModelFile
{
     .....
     public string Path{ get; set; }
     public ICollection<IFormFile> Upload { get; set; }
}


public async Task<IActionResult> Index([Bind("Upload,Path")] ModelFile modelfile)
{
     ...
     msg = await storeFilesInServer(modelfile.Upload,modelfile.Path);
}


private async Task<Message> storeFilesInServer(ICollection<IFormFile> upload, string path)
        {
            Message msg = new Message();
            msg.Status = "OK";
            msg.Code = 100;
            msg.Text = "File uploaded successfully";
            msg.Error = "";
            string tempFileName = "";
            try
            {
                foreach (var file in upload)
                {
                    if (file.Length > 0)
                    {
                        string tempPath = path + @"\";
                        if (Request.Host.Value.Contains("localhost"))
                            tempPath = path + @"\"; 

                        using (var fileStream = new FileStream(tempPath + file.FileName, FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                            tempFileName = file.FileName;
                        }
                    }
                    msg.Text = tempFileName;
                }
            }
            catch (Exception ex)
            {
                msg.Error = ex.Message;
                msg.Status = "ERROR";
                msg.Code = 301;
                msg.Text = "There was an error storing the files, please contact support team";
            }

            return msg;
        }
0 голосов
/ 24 августа 2010

У меня нет VS, чтобы смоделировать вашу проблему.Так что я не уверен насчет ответа.

Попробуйте, возможно, сработает

<input type="file" name="model.FilePath" id="file" />

Если не сработает, попробуйте поискать его на вашем собрании форм & HttpContext.Request.Files

Это должно быть там.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...