c# - .NET Core - Web API - 如何进行文件上传?

标签 c# asp.net-core file-upload servlet-3.0

我无法弄清楚如何编写 .NET Core Web API 来支持文件上传。请注意,我没有使用 ASP.NET Core MVC 表单来上传文件,而是通过 Servlet/JSP 容器。 这是我的 project.json 的定义方式,

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Npgsql": "3.1.9",
    "CoreCompat.Newtonsoft.Json": "9.0.2-beta001",
    "Newtonsoft.Json": "9.0.1"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

这是我的Startup的定义方式,

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

using QCService.Models;

namespace QCService
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            //Add SurveysRepository for Dependency Injection
            services.AddSingleton<ISurveysRepository, SurveysRepository>();
            //Add FeedbacksRepository for Dependency Injection
            services.AddSingleton<IFeedbacksRepository, FeedbacksRepository>();
            //Add AttachmentsRepository for Dependency Injection
            services.AddSingleton<IAttachmentsRepository, AttachmentsRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();
        }
    }
}

最后这是我的 Controller 的定义方式,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
//Including model classes for Attachments
using QCService.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Microsoft.Net.Http.Headers;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace QCService.Controllers
{
    [Route("api/[controller]")]
    public class AttachmentsController : Controller
    {
        public IAttachmentsRepository AttachmentItems { get; set; }
        public AttachmentsController(IAttachmentsRepository attachmentItems)
        {
            AttachmentItems = attachmentItems;
        }

        // GET: api/Attachments
        [HttpGet] /*http://localhost:52770/api/Attachments*/
        public IEnumerable<Attachments> Get()
        {
            return AttachmentItems.GetAllAttachments();
        }

        // GET api/Attachments/5
        [HttpGet("{id}")] /*http://localhost:52770/api/Attachments/{AttachmentID}*/
        public Attachments Get(int id)
        {
            return AttachmentItems.GetAttachment(id);
        }

        // GET api/Attachments/5
        [HttpGet("Feedback/{id}")] /*http://localhost:52770/api/Attachments/Feedback/{FeedbackID}*/
        public IEnumerable<Attachments> GetFeedbackAttachments(int id)
        {
            return AttachmentItems.GetFeedbackAttachments(id);
        }

        // POST api/Attachments
        [HttpPost]/*http://localhost:52770/api/Attachments/*/
        public async Task<IActionResult> PostFiles(ICollection<IFormFile> files)
        {
            try
            {
                System.Console.WriteLine("You received the call!");
                WriteLog("PostFiles call received!", true);
                //We would always copy the attachments to the folder specified above but for now dump it wherver....
                long size = files.Sum(f => f.Length);

                // full path to file in temp location
                var filePath = Path.GetTempFileName();
                var fileName = Path.GetTempFileName();

                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await formFile.CopyToAsync(stream);
                            //formFile.CopyToAsync(stream);
                        }
                    }
                }

                // process uploaded files
                // Don't rely on or trust the FileName property without validation.
                //Displaying File Name for verification purposes for now -Rohit

                return Ok(new { count = files.Count, fileName, size, filePath });
            }
            catch (Exception exp)
            {
                System.Console.WriteLine("Exception generated when uploading file - " + exp.Message);
                WriteLog("Exception generated when uploading file - " + exp.Message, true);
                string message = $"file / upload failed!";
                return Json(message);
            }
        }

        /// <summary>
        /// Writes a log entry to the local file system
        /// </summary>
        /// <param name="Message">Message to be written to the log file</param>
        /// <param name="InsertNewLine">Inserts a new line</param>
        public void WriteLog(string Message, bool InsertNewLine)
        {
            LogActivity ologObject = null;
            try
            {
                string MessageString = (InsertNewLine == true ? Environment.NewLine : "") + Message;
                if (ologObject == null)
                    ologObject = LogActivity.GetLogObject();
                ologObject.WriteLog(Message, InsertNewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to write to the log file : " + ex.Message);
                Console.WriteLine("Stack Trace : " + ex.StackTrace);
            }
        }
    }
}

我已经浏览过这个链接, https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads 但就是无法让它发挥作用! 如有任何帮助,我们将不胜感激!!!

我正在使用 Google 的高级 Rest 客户端发布数据,如下所示, This is how I am sending the POST request

我不断收到以下消息的响应失败... 地位: 500内部服务器错误 加载时间:62 毫秒 响应 header 5 请求 header 2 重定向 0 时间安排 内容类型:多部分/表单数据;边界=----WebKitFormBoundary0RKUhduCjSNZOEMN 内容长度:9106 消息来源

POST/api/附件 HTTP/1.1 主机:本地主机:52770 内容类型:多部分/表单数据;边界=----WebKitFormBoundary0RKUhduCjSNZOEMN 内容长度:9106

------WebKitFormBoundary0RKUhduCjSNZOEMN 内容处置:表单数据;名称=“文件上传1”;文件名=“1i4ymeoyov_In_the_Wild_Testing.png” 内容类型:图像/png

.PNG

IHDR,I�3(tEXtSoftwareAdobe ImageReadyq�e< iTXtXML:com.adobe.xmp�8 ^2IDATx��] pU����@ a�H� Pe�P8 ����b�̌3�p�q�*�7"�h�+Yf��O�atD��(<� h|DLXdOH ������=}����}ov8_U�..... ------WebKitFormBoundary0RKUhduCjSNZOEMN--

最佳答案

这就是根本原因:form-data;名称=“文件上传1”

您的名称“fileUpload1”必须是“files”,与操作 PostFiles(ICollection< IFormFile> files) 的声明相匹配

关于c# - .NET Core - Web API - 如何进行文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42235485/

相关文章:

docker - 未从dockerfile发布具有Net Core 3.1 API的Dockerfile

amazon-web-services - Amazon S3 如何在 “folder” 中列出文件

c# - C#中如何调用基于XML-RPC规范的API?

asp.net-core - 我的 Entity Framework Core API 在本地工作正常,但在生产中失败并出现 405 错误

c# - 如何在 C# 中使用 LUIS None Intent 而无需 LUIS 的火车话语

c# - 如何从 ASP.NET Core RC2 Web Api 返回 HTTP 500?

php - 可恢复上传到谷歌驱动器,但服务帐户错误

java - 使用 http PUT 上传的文件在服务器上的大小不准确

c# - 面向对象的嵌套字典数据结构

c# - 遍历所有颜色?