简体   繁体   中英

How to implement an upload form in .Net Core API?

I create a .Net Core API ( I use swagger with it).

I create a controller in order to upload a picture to link it to an item.

.cs :

[HttpPut("[Action]/{id}")]
public async Task<ActionResult> Link(int id, IFormFile file)
{
    var item = await _context.Item.FirstOrDefaultAsync(t => t.Id == id);
    if (item == null)
    {
        return BadRequest("item null");
    }

    using (var memoryStream = new MemoryStream())
    {
        await file.CopyToAsync(memoryStream);
        // code to link
        return Ok(file);
    }
}

My issue is if I want to test to know if it works, I have to use postman but I want to test it in my api.

A solution exist for my issue ? For the moment it look like that : 上传文件

For Swashbuckle.AspNetCore with 4.0.1 and Swashbuckle.AspNetCore.Swagger with 4.0.1 , it supports IFormFile with swagger/index.html .

Detail steps:

  1. Install package Swashbuckle.AspNetCore with 4.0.1 and Swashbuckle.AspNetCore.Swagger with 4.0.1
  2. Startup.cs

     public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseMvc(); } } 
  3. ApiController

     [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { [HttpPut("[Action]/{id}")] public async Task<ActionResult> Link(int id, IFormFile file) { return Ok(id); } } 

IFormFile only works for multipart/form-data encoded requests. To send via JSON, you need to bind to byte[] , and then send the file data as either a Base64-encoded string or a uint array (ie the JSON equivalent of a byte[] .

Also, JSON is an object notation format, so you must bind to an object. For example:

public class MyFileUploadModel
{
    public byte[] File { get; set; }
}

Then:

public async Task<IActionResult> Link(int id, MyFileUploadModel model)

Finally, you'd send a JSON object like:

{
    "file": "[base64 encoded string here]"
}

OR

{
    "file": [1, 2, 3]
}

Where [1, 2, 3] would actually be an array of the bytes in the file (ie numbers 0-255).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM