Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

azure - asp.net core web API file upload and "form-data" multiple parameter passing to method

I have created an endpoint that takes files as parameters:

    [HttpPost("[action]")]
    [Consumes("multipart/form-data")]
    public ActionResult UploadImage(IFormFile  Files, string param)
    {

        long size = Files.Length;            
        var tempPath = Path.GetTempFileName();
        string file_Extension = Path.GetExtension(Files.FileName);                   
        var isValidFile = FileValidation.FileUploadValidation(Files);
        if (isValidFile.data)
        {
            string filename = Guid.NewGuid() + "" + file_Extension;
            return null;

        }
        else
        {
            return null;
        }
    }

I cant retrieve the file with out a issue. How to add more text parameters to the same method ?

Debug View param parameter is null

Postmen call

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It works 100%. Tested. Please do the below steps:

You should create a custom class for the model as

public class FileInputModel
{
    public string Name { get; set; }
    public IFormFile FileToUpload { get; set; }
}

and the form like

<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFileViaModel" >
    <input name="Name" class="form-control" />
    <input name="FileToUpload" type="file" class="form-control" />
    <input type="submit" value="Create" class="btn btn-default" />
</form>

and the controller method like

[HttpPost]
public async Task<IActionResult> UploadFileViaModel([FromForm] FileInputModel model)
{
    if (model == null || model.FileToUpload == null || model.FileToUpload.Length == 0)
        return Content("file not selected");

    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", model.FileToUpload.FileName);

    using (var stream = new FileStream(path, FileMode.Create))
    {
        await model.FileToUpload.CopyToAsync(stream);
    }

    return RedirectToAction("Files");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...