2016-10-18 2 views
0

나는 이미지 업로드를 위해 asp.net 코어 및 웹 API를 사용하고 있습니다."Alternate"속성을 서버의 이미지 파일에 추가하는 방법은 무엇입니까?

클라이언트에서
[Produces("application/json")] 
[Route("api/Upload")] 
public class UploadApiController : Controller 
{ 
    private readonly IHostingEnvironment _environment; 

    public UploadApiController(IHostingEnvironment environment) 
    { 
     _environment = environment; 
    } 

    [HttpPost] 
    public async Task Post(ICollection<IFormFile> files) 
    { 
     //... 
    } 
} 

:

// Files is an array that contains all temporary images for uploading. 
let Files = []; 

let image_preview = function (file) { 
    file['Alternate'] = 'alternate_text'; 
    Files.push(file); 

    // other implements... 
}; 

$('button#upload').click(function() { 
    let formData = new FormData(); 

    for (let i = 0; i < Files.length; i++) { 
     formData.append('files', Files[i]) 
    } 

    let xhr = new XMLHttpRequest(); 
    xhr.open('POST', '/api/upload', true); 

    xhr.onload = function() { 
     console.log('uploading...') 
    }; 

    xhr.send(formData); 
}); 

스냅 샷 :

1

내 질문 : ICollection<IFormFile> files에 새 속성 "대체"를 추가하는 방법을 감지하는 서버에서

에서 보낸 Alternate 속성 클라이언트 (formData)?

답변

0

질문은 How to add property “Alternate” to an image file on server?에 대한 대답이 아니지만 문제를 해결하는 것처럼 보입니다 (대체 텍스트가 포함 된 이미지 파일 전송). 서버에서

:

클라이언트에서
using Newtonsoft.Json; 

[HttpPost] 
public async Task Post(ICollection<IFormFile> files, IList<string> alts) 
{ 
    IDictionary<string, string> _alts = new Dictionary<string, string>(); 

    foreach (var alt in alts) 
    { 
     IDictionary<string, string> temp = JsonConvert.DeserializeObject<Dictionary<string, string>>(alt); 

     foreach (var item in temp) 
     { 
      _alts.Add(item.Key, item.Value); 
     } 

    } 
} 

: 우리가 '경우 Files[i]['name'] 항상 주이며, (누군가에 의해 해킹) 변경할 수 없기 때문에

for (let i = 0; i < Files.length; i++) { 
    formData.append('files', Files[i]); 

    let name = Files[i]['name'], 
     alt = {}; 

    alt[name] = 'alt_text'; 

    formData.append('alts', JSON.stringify(alt)); 
} 

우리는 사전에 중복 키를 얻을하지 않을 것 중복 업로드 파일을 확인했습니다.

그런 다음 Key의 파일 이름 (files)을 _alts에 병합하여 대체 텍스트를 얻을 수 있습니다.

스냅 샷 :

2

UPDATE : 스냅 샷 코드가 잘못되었습니다.

관련 문제