Struggle with file upload .net core MVC

Viewed 319

after days of googling and trying i am not able to have xsd-files uploaded to the webserver.

Here you see the create form:

<form asp-action="Create" enctype="multipart/form-data" method="post">
<input asp-for="catname" class="form-control" />
<input type="file" asp-for="xsddata" class="form-control" />
<input type="submit" value="Create" class="btn btn-primary" />
</form>

The model looks like this:

public class cat{
[Key]
public int catid { get; set; }
public string catname { get; set; }
public string xsddata { get; set; }}

and I only want to save the path & filename in the database.

Within the controller-class I have added the method for saving:

[HttpPost]
    public async Task<IActionResult> Upload([FromForm]IFormFile file)
    {
        var path = Startup.myAppPath();
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        FileInfo fileInfo = new FileInfo(file.FileName);
        var fullPath = Path.Combine(path, fileInfo.Name);
        if (!System.IO.File.Exists(fullPath))
        {
            using (FileStream fileStream = new FileStream(fullPath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            return new JsonResult(new { FileName = fileInfo.Name });
        }
        return BadRequest();
    }

But right now, the IDE crashes even after I have choosen a file and before I hit the 'submit' button.

This drives me crazy for days, and I cannot find an example to rely on. Would be nice if you guys might help me out.

1 Answers

My suggestion is that: Why your IDE would crash after you choose a file and before submit it? Do you try to choose some files of different sizes?

In your controller, the code has nothing to do with the model, you can try to change some codes.

First, change the type of ‘xsddata’ in model :

Model:

public class Cat
{
[Key]
public int catid { get; set; }
public string catname { get; set; }
public IFormFile xsddata { get; set; }
}

View:

<div>
<h4>File in Model Upload</h4>
<form asp-controller="Home" asp-action="FileUpLoad" enctype="multipart/form-data" method="post">
<input type="text" name="cat.catid" />
<input type="text" name="cat.catname" />
<input type="file" name=cat.xsddata />
<button type="submit">Submit</button>
</form>
</div>

You can get this form ,Fill in the catid and catname ,choose a file and submit it:

enter image description here

Then ,you can receive the value in the controller:

enter image description here

Related