2017-02-14 158 views
6

Dosya Yükleme'yi desteklemek için bir .NET Çekirdek Web API'sinin nasıl yazılacağını anlayamıyorum. Lütfen dosya yükleme için bir Servlet/JSP kapsayıcısı kullanarak ASP.NET Çekirdek MVC formunu kullanmıyorum. Burada.NET Core - Web API - Dosya Yükleme nasıl yapılır?

Son olarak burada, İşte
{ 
    "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%" ] 
    } 
} 

benim Başlangıç ​​ tanımlanır nasıl benim project.json nasıl tanımlandığını

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

benim Kontrolör tanımlanır nasıl

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

nk, https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads ancak bunu yapamazsınız! Herhangi bir yardım için teşekkür ederiz! Ben şöyle veri göndermek için Google'ın Gelişmiş istirahat Client kullanıyorum

, ben tepkisini almaya devam This is how I am sending the POST request

aşağıdaki iletiyle başarısız ... Durum: 500: Internal Server Error yükleme süresi: 62 msn Tepki başlıkları istek başlıklarında Yönlendirme Zamanlamaları Content-Type: Çok parçalı/form-data; Sınır = ---- WebKitFormBoundary0RKUhduCjSNZOEMN İçerik-Uzunluk: 9106 Kaynak mesajı

POST/api/Ekler HTTP/1.1 HOST: localhost: 52770 içerik türü: Çok parçalı/form-data; Sınır = ---- WebKitFormBoundary0RKUhduCjSNZOEMN içerik uzunluğu: 9106

------ WebKitFormBoundary0RKUhduCjSNZOEMN Content-Disposition: form-; = "FileUpload1" adını; filename = "1i4ymeoyov_In_the_Wild_Testing.png" Content-Type: image/png

PNG

IHDR, I3 (tEXtSoftwareAdobe ImageReadyqe < iTXtXML: com.adobe.xmp 8 ^ 2IDATx ] pU @ a H Pe P8 Ȉ b ̌3 p q * 7 " h + YF O atD (< h¦DLXdOH ) =}} ov8_U ..... ------ URL doğru değil, request yılında

+0

Not olmak zorunda MVC ve Web API (sadece Bilginize) .. yanıtlarken için – ssmith

cevap

0

WebKitFormBoundary0RKUhduCjSNZOEMN--., denetleyici üzerine rotasını kontrol [Route ("api/[controller]")] ve eylem yöntemi adı PostFiles'dur. Yani, doğru URL http://localhost:52770/api/Attachments/PostFiles

Ya URL'yi düzeltmek yoksa o konu krom 56 bir hatadan dolayı olduğunu düşünüyorum Index

+0

Pradeep teşekkürler. – Rohit

+0

Her iki yolu da denedim, ancak şans yok. URL'yi 'http: // localhost: 52770/api/Attachments/PostFiles' olarak kullanırsam HTTP 404'ü yanıt olarak alırım. İşlem yöntemini Dizin olarak yeniden tanımlarsam, yanıt olarak '500: Dahili Sunucu Hatası' alırım. .NET Çekirdek Web API isteği yazabilmek için kullanılan 'Google'ın ARC' dosyaları seçerken ben dosyalara parametrenin adını güncelledik unutmayınız. Eğer Index olarak eylem yöntemi adını kullanırsanız – Rohit

+0

, sen ayıklama için eylem yöntemine elde edebiliyoruz? Bir şey daha, Path.GetTempFileName(), kullanıcının geçici klasöründe geçici bir dosya oluşturur. Uygulama bunu yapma iznine sahip olmayabilir. farklı bir yol var yüklenenler = Path.Combine (_environment.WebRootPath, "yüklenenler") deneyin; foreach (dosyalardaki var dosyaları) {if (dosya.Length> 0) {using (var fileStream = yeni FileStream (Path.Combine (karşıya yüklenenler, dosya.FileName), FileMode.Create)) { sizden bekliyoruz.CopyToAsync (Filestream);} } } –

0

olarak eylem yöntemini adlandırmak olacaktır.Çok parçalı/formu-verileri:

ARC can't send files on new Chrome version: 56.0.2924.76

Bu sorun basit bir çözüm Kullanım XHR seçeneği etkinleştirmek ve başlık Content-Type kaldırmak hem postacı ve ChromeRestClient

etkiler.

Bu Bu kök nedenidir

4

postacı ve krom ikisi için çalışır: form-data; = "FileUpload1" adını

Adınız "fileUpload1" eylem PostFiles beyanı maçları "dosyalar" (ıcollection < IFormFile> dosyaları) ASP.NET Çekirdeği hiçbir ayrım arasında olduğunu