当前位置: 首页 > 知识库问答 >
问题:

.NET核心-Web API-如何进行文件上载?

鞠凌龙
2023-03-14

我搞不懂,怎么写一本书。NET核心Web API支持文件上传。请注意,我没有使用ASP。NET核心MVC表单,用于文件上载,但通过Servlet/JSP容器。以下是我的项目是如何完成的。定义了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%" ]
  }
}

以下是我的创业定义,

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();
        }
    }
}

最后这里是如何定义我的控制器,

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://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads但就是做不到!任何帮助都很感激!!!

我正在使用谷歌的高级Rest客户端发布数据,如下所示,这就是我发送post请求的方式

我不断收到响应失败,出现以下消息。。。状态:500:内部服务器错误加载时间:62毫秒响应头5请求头2重定向0计时内容类型:多部分/表单数据;boundary=--WebKitFormBoundary0RKUDucJsnzoemn内容长度:9106源消息

POST/api/Attachments HTTP/1.1主机:localhost:52770内容类型:多部分/表单数据;边界=----WebKitFormBoundary0RKUDucJsnzoemn内容长度:9106

------WebKitFormBoundary0RkuducJsnzoemn内容配置:表单数据;name=“fileUpload1”;filename=“1i4ymeoyov\u In\u the\u Wild\u Testing.png”内容类型:image/png

PNG

IHDR, I 3(tEXtSoftwareAdobe ImageReadyq e

共有3个答案

夹谷野
2023-03-14

在请求中,您的URL不正确。检查控制器上的路由,它是[route(“api/[controller]”),操作方法名称是PostFiles。因此,正确的URL将是http://localhost:52770/api/Attachments/PostFiles

请更正URL或将操作方法重命名为索引

颛孙哲
2023-03-14

Hi将ContentType从“多部分/表单数据”更改为“应用程序/八位字节流”。在代码块内移动时没有错误。请尝试以下以二进制类型发送文件的代码:

byte[] fileToSend = File.ReadAllBytes(filePath);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/octet-stream";
httpWebRequest.ContentLength = fileToSend.Length;              

using (Stream requestStream = httpWebRequest.GetRequestStream())
{
    requestStream.Write(fileToSend, 0, fileToSend.Length);
    requestStream.Close();
}

希望它会工作...谢啦

贾俊艾
2023-03-14

这是根本原因:表单数据;name=“fileUpload1”

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

 类似资料:
  • 我想知道,当我们为客户提供新的更新时,是否有丢失这些文件的风险。如果有更好的解决方案,上传文件和获取文件链接之后,与.NET core请告诉我:)

  • .NET核心和ASP.NET核心到底有什么区别?

  • 我正在为PoC点构建我的dotnet core webapi服务,我关心的是为其他ARCH/Devs提供适当的指导。 “相同”方法签名的变化很少 公共动态获取(字符串名称=_defaultName) 公共IActionResult Get(字符串名称=_DefaultName) 获取公共异步任务(字符串名称=_defaultName) 撇开我为什么使用动态类型而不是自定义类型的讨论不谈,我试图理解

  • 当.NET Core仍然使用格式时,您可以构建一个针对多个框架(例如net451、NETCoreApp1.0)的类库。 现在正式的项目格式是使用MSBuild的,那么如何指定多个框架作为目标呢?我试图从VS2017中的项目设置中寻找这一点,但我只能针对.NET核心框架中的一个框架(它甚至没有列出我确实安装的其他完整的.NET framework版本):

  • 我已经创建了非核心webapi项目来与移动应用程序交互。例如,如果我创建了一个名为Data的控制器,它有一个名为Search的方法,如下图所示。该项目已配置为发送和接收json数据。 我可以通过使用以下url,使用postman向该方法发送post请求http://localhost/api/Data/search 类似地,我可以在控制器内创建其他函数,并使用路由“/api/[controller