简体   繁体   English

.NET Core Web API中的图像上传

[英]Image upload in .NET Core Web API

I'm developing a Web API with .Net Core, where I need to allow a client to upload a list of files (mostly images) and save them to the server. 我正在使用.Net Core开发Web API,我需要允许客户端上传文件列表(主要是图像)并将其保存到服务器。

Im using ASP.NET Core 3.0 我正在使用ASP.NET Core 3.0

This is my startup file Startup.cs: 这是我的启动文件Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;


namespace ImageUplaodDemo
{
    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.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment 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();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

This is my ImageController file ImageController.cs: 这是我的ImageController文件ImageController.cs:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ImageUploadDemo.Controllers
{
    [Route("api/[controller]")]
    public class ImageController : ControllerBase
    {
        public static IHostingEnvironment _environment;
        public ImageController(IHostingEnvironment environment)
        {
            _environment = environment;
        }
        public class FIleUploadAPI
        {
            public IFormFile files { get; set; }
        }
        [HttpPost]
        public async Task<string> Post(FIleUploadAPI files)
        {
            if (files.files.Length > 0)
            {
                try
                {
                    if (!Directory.Exists(_environment.WebRootPath + "\\uploads\\"))
                    {
                        Directory.CreateDirectory(_environment.WebRootPath + "\\uploads\\");
                    }
                    using (FileStream filestream = System.IO.File.Create(_environment.WebRootPath + "\\uploads\\" + files.files.FileName))
                    {
                        files.files.CopyTo(filestream);
                        filestream.Flush();
                        return "\\uploads\\" + files.files.FileName;
                    }
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
            }
            else
            {
                return "Unsuccessful";
            }
        }
    }
}

Im trying to upload a image using POSTMAN by POST operation. 我试图通过POST操作使用POSTMAN上传图像。 I assigned REQUEST to POST and im using form-data under Body tag and assigned KEY as file to upload a file from the desktop. 我使用Body标记下的表格数据将REQUEST分配给POST和即时消息,并将KEY分配为文件以从桌面上载文件。 But im getting the following error. 但即时通讯收到以下错误。

I have tried all possible but been getting the same error... 我已经尝试了所有可能的方法,但是却遇到了相同的错误...

Check through the code once and there any modification need to be done on the code or any modifications on postman.... 仔细检查一下代码,是否需要对代码进行任何修改或对邮递员进行任何修改。

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "detail": null,
    "instance": null,
    "extensions": {
        "traceId": "|2c45b532-43521b159e7b734f."
    }
}

Remove these lines: 删除这些行:

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Controller didn't find anything!");
});

You're short-circuiting every request and just returning "Controller didn't find anything!" 您正在短路每个请求,然后返回“ Controller没找到任何东西!” with that. 接着就,随即。 Nothing ever even makes it into the pipeline. 没有任何东西可以进入管道。

Hey have you tried the official docus? 嘿,您尝试过正式的配色吗?

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2 https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2

and this one https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio 还有一个https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio

I would try to use official sources to learn topics like this, instead of random blogs. 我会尝试使用官方资源来学习类似的主题,而不是随机博客。

Have you debugged your controller? 您调试了控制器吗? Is the IFormFile in your viewmodel already mapped? 您的视图模型中的IFormFile是否已映射?

The controller should be found automatically and respond to: 应该自动找到控制器并响应:

http(s)://localhost:DEVPORT/api/Image HTTP(S)://本地主机:DEVPORT / API /图像

You could add an Index Endpoint returning a string "Hello World" and you should see a Json Response , when you try to connect with your browser.. 您可以添加一个返回字符串“ Hello World”的索引端点,当您尝试与浏览器连接时,应该会看到Json Response。

Not sure why you are doing this: 不知道为什么要这样做:

app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Controller didn't find anything!");
            });

Did you send the right body in your post request? 您是否在发帖请求中发送了正确的正文?

[HttpPost("UploadFile")]
 public async Task<string> UploadFile([FromForm] IFormFile file)
    {
        string fName = file.FileName;
        string path = Path.Combine(hostingEnvironment.ContentRootPath, "Images/" + file.FileName);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
        return file.FileName; 
    }

You can use this in your controller class. 您可以在控制器类中使用它。 Don't need to create a FileUploadAPi class. 不需要创建FileUploadAPi类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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