.NET Core Web API中的图像上传 [英] Image upload in .NET Core Web API

查看:985
本文介绍了.NET Core Web API中的图像上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.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.

我正在使用ASP.NET Core 3.0

Im using ASP.NET Core 3.0

这是我的启动文件
Startup.cs:

This is my startup file 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:

This is my ImageController file 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尝试使用POSTMAN通过POST操作上传图像。
我将请求分配给POST,并使用Body标记下的表格数据将即时消息分配给了我,并分配了KEY作为文件,以便从桌面上传文件。但是我收到以下错误。

Im trying to upload a image using POSTMAN by POST operation. 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. 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."
    }
}


推荐答案

[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类。

You can use this in your controller class. Don't need to create a FileUploadAPi class.

这篇关于.NET Core Web API中的图像上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆