簡體   English   中英

.NET Core Web API中的圖像上傳

[英]Image upload in .NET Core Web API

我正在使用.Net Core開發Web API,我需要允許客戶端上傳文件列表(主要是圖像)並將其保存到服務器。

我正在使用ASP.NET Core 3.0

這是我的啟動文件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();
            });
        }
    }
}

這是我的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";
            }
        }
    }
}

我試圖通過POST操作使用POSTMAN上傳圖像。 我使用Body標記下的表格數據將REQUEST分配給POST和即時消息,並將KEY分配為文件以從桌面上載文件。 但即時通訊收到以下錯誤。

我已經嘗試了所有可能的方法,但是卻遇到了相同的錯誤...

仔細檢查一下代碼,是否需要對代碼進行任何修改或對郵遞員進行任何修改。

{
    "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."
    }
}

刪除這些行:

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

您正在短路每個請求,然后返回“ Controller沒找到任何東西!” 接着就,隨即。 沒有任何東西可以進入管道。

嘿,您嘗試過正式的配色嗎?

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

還有一個https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio

我會嘗試使用官方資源來學習類似的主題,而不是隨機博客。

您調試了控制器嗎? 您的視圖模型中的IFormFile是否已映射?

應該自動找到控制器並響應:

HTTP(S)://本地主機:DEVPORT / API /圖像

您可以添加一個返回字符串“ Hello World”的索引端點,當您嘗試與瀏覽器連接時,應該會看到Json Response。

不知道為什么要這樣做:

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

您是否在發帖請求中發送了正確的正文?

[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; 
    }

您可以在控制器類中使用它。 不需要創建FileUploadAPi類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM