ASP.Net Core: проблемы с загрузкой файлов - блокировка файлов и 404-е - PullRequest
0 голосов
/ 22 марта 2019

У меня есть метод контроллера, который загружает файл для определенных интерфейсов. Допускается только 1 документ на интерфейс, имя файла всегда одинаково и, следовательно, заменяет предыдущее для этого интерфейса. Загрузка файла в первый раз работает нормально, но при попытке загрузить другой в тот же интерфейс вскоре после этого это невозможно, поскольку файл заблокирован. Я пытаюсь решить эту проблему, но даже при этом страница возвращает ошибку HTTP 404. Как остановить блокировку файла и почему я получаю 404? (Работает локально)

Метод контроллера:

 public async  Task<IActionResult>  Documentation(DocUpload document)
    {
        if (document.Document != null)
        {
            // do other validations on your model as needed
            try
            {

                string fileName = "Interface-" + document.InterfaceId + "-Documentation" +
                                        Path.GetExtension(document.Document.FileName);
                string doucumentationPath = Path.Combine(_hostingEnvironment.WebRootPath, "documentation");
                string filePath = Path.Combine(doucumentationPath, fileName);

                await document.Document.CopyToAsync(new FileStream(filePath, FileMode.Create));
                string fileUrl = "~/documentation/" + fileName;

                document = new DocUpload();
                if (_context != null)
                {
                    Dictionary<int, string> interfaces = _context.Interfaces.OrderBy(x => x.InterfaceName)
                        .ToDictionary(x => x.InterfaceID, x => x.InterfaceName);
                    document.Interfaces = interfaces;
                }
                document.Message = "Documentation upload complete";
                document.InterfaceId = -1;

            }
            catch (Exception e)
            {
                document.Error = true;
                document.Message = "The has been a problem uploading the documentation:" + Environment.NewLine +
                                   e.Message;
            }

            //to do save to db   


        }

        return View(document);

    }

Вид:

    @model DocUpload

@section Scripts
{
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}

@{
    ViewData["Title"] = "Documentation";

}

<h2>Upload Documentation</h2>

<div class="alert alert-warning">
    <strong>Warning:</strong> Any existing documentation for the selected interface will be overwritten
</div>

@if(!string.IsNullOrEmpty(Model.Message))
{
    var alertClass = Model.Error ? "alert alert-danger" : "alert alert-success";

    <div class="@alertClass" role="alert">
        @Model.Message
    </div>
}

    <form asp-controller="Interfaces" asp-action="Documentation" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label asp-for="InterfaceId"></label>
        <select asp-for="InterfaceId"  asp-items="@(new SelectList(Model.Interfaces, "Key", "Value"))"  >
            <option value="-1">Choose ...</option>
        </select>
        <span asp-validation-for="InterfaceId" class="text-danger"></span>

    </div>
    <div class="form-group">
        <input asp-for="Document" class="form-control-file" />
        <span asp-validation-for="Document" class="text-danger"></span>
    </div>
    <div class="form-group">
        <input type="submit" class="btn btn-primary"/>
    </div>

</form>

Модель:

public class DocUpload
{

    public Dictionary<int,string> Interfaces { get; set; }
    [Required(ErrorMessage = "Please select a document to upload.")]
    public IFormFile Document { get; set; }
    [Required()]
    [Display(Name = "Interface")]
    [Range(0, 100000, ErrorMessage = "You must select an interface to associate the document to.")]
    public int InterfaceId { get; set; }

    public bool Error { get; set; }
    public string Message { get; set; }
}

1 Ответ

0 голосов
/ 25 марта 2019

Эта ошибка вызвана тем, что вы не располагали потоком файлов.

Попробуйте код ниже:

public async Task<IActionResult> Documentation(DocUpload document)
{
    if (document.Document != null)
    {
        // do other validations on your model as needed
        try
        {
            string fileName = "Interface-" + document.InterfaceId + "-Documentation" +
                                    Path.GetExtension(document.Document.FileName);
            string doucumentationPath = Path.Combine(_hostingEnvironment.WebRootPath, "documentation");
            string filePath = Path.Combine(doucumentationPath, fileName);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await document.Document.CopyToAsync(stream);
            }
            string fileUrl = "~/documentation/" + fileName;
        }
        catch (Exception e)
        {
            document.Error = true;
            document.Message = "The has been a problem uploading the documentation:" + Environment.NewLine +
                                e.Message;
        }
        //to do save to db  
    }
    return View(document);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...