2017-09-04 55 views
1

我的文件在棱角的端格式如下:如何從角(2/4)在ASP.NET核心的WebAPI服務器文件夾傳送圖像

let fi = this.fileInput.nativeElement; 
let fileToUpload = fi.files[0]; 

let input = new FormData(); 
input.append("file", fileToUpload); 

return this.http.post(uploadUrl, input); 

和我的ASP.NET核心API是:

[HttpPost] 
public IActionResult Post([FromBody]JObject objData) 
{ 
    dynamic jsonData = objData; 
    JObject FileJson = jsonData.jsonFile; // JSON File 

    // Please suggest how to store the file in Folder 
} 

在此先感謝

+0

一般我們不會發送'圖片'作爲'Json'格式,但是以'多部分'的形式,並使用'stream-object',您可以將圖像保存在服務器中。 – Webruster

+0

是!我明白了。感謝您的答覆 :) –

回答

0

我已經想通了。所以我發佈了答案,以便它可以幫助其他人。

這是我在ASP.NET核心API控制器完整代碼:

public class FileUploadController : Controller 
{ 
    private IHostingEnvironment _env; 
    public FileUploadController(IHostingEnvironment env) 
    { 
     _env = env; 
    } 
    [HttpPost] 
    public IActionResult Upload(IFormFile file) 
    { 

     long size = 0; 

      var filename = ContentDispositionHeaderValue 
          .Parse(file.ContentDisposition) 
          .FileName 
          .Trim('"'); 


     var webRoot = _env.WebRootPath; 

     var filePath = webRoot + "/Uploads" + [email protected]"/{ filename}"; 

     bool fileExists = (System.IO.File.Exists(filePath) ? true : false); 

     if (fileExists) 
     { 
      Random random = new Random(); 
      var randomNum = random.Next(99999); 
      filename = randomNum +filename; 
      filePath = webRoot + "/Uploads" + [email protected]"/{ filename}"; 
     } 
     size += file.Length; 
      using (FileStream fs = System.IO.File.Create(filePath)) 
      { 
       file.CopyTo(fs); 
       fs.Flush(); 
      } 
     return Ok(filename); 
    } 
} 

這在我圖片上傳服務在角:

export class UploadService { 
    constructor(private http: Http) { } 

    public upload = function (fileToUpload: any, uploadUrl) { 

    let input = new FormData(); 
    input.append("file", fileToUpload); 

    return this.http.post(uploadUrl, input); 
    } 
} 

這是我documentSubmit功能角度分量

import { UploadService } from './Upload.service';

constructor(private http: Http,private uploadService: UploadService) { }

@ViewChild("fileInput") fileInput;

onDocumentSubmit = function() { 

    let fi = this.fileInput.nativeElement; 

    if (fi.files && fi.files[0]) { 

    let fileToUpload = fi.files[0]; 

    this.uploadService.upload(fileToUpload, ConstantComponent.url + "/FileUpload") 
    .subscribe(data => { 

     let documentDetails = { 
     PodId: this.podId, 
     DocumentName: fileToUpload.name, 
     DocumentPath: ConstantComponent.port + "/Uploads/" + data._body, 
     } 
     this.http.post(ConstantComponent.url + "/DocumentManagerAPI/Add", documentDetails, options) 
     .map((res: Response) => res.json()).subscribe(
     data => { 
      console.log("success") 

     }, error => { 
      console.log("error") 

     }); 
    }); 
    } 
} 

這是我的文件輸入HTML

<input #fileInput type="file" #select name="document" [(ngModel)]="document" />

相關問題