2014年4月7日 星期一

File upload with Html5 & WebApi & SignalR (1)

File upload with Html5 & WebApi & SignalR (1)
Author : JB

The architecture is showed as below.

This article separates into three parts :

1.  Web API with async upload method.
2.  Add SignalR framework to the Web API.
3.  Implement the front-end.


1.  First, add a Web API project and upgrade the latest one in Nuget. We may encounter a CORS issue in this upload architecture, so make sure to have Web API 2.1 Cross-Origin Support as well.


2.  So here is the upload (POST) method in Controller :

private readonly String CENTER_FILE_PATH = @"D:\TEMP\FileCenter";

// POST api/file/Upload
[
HttpPost, ActionName("Upload")]
public async Task<HttpResponseMessage> Post()
{

  
try
  
{
     
//Create if necessary
     
this.createCenterDirectory(uploadPath);
     
//Check if the request contains multipart/form-data.
     
if (!Request.Content.IsMimeMultipartContent())
     {
        
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
     }
    
//Start Reading multi-part from request
    
var streamProvider = new MultipartFormDataStreamProvider(uploadPath);
    
await Request.Content.ReadAsMultipartAsync(streamProvider);
    
//For each MultipartFileData, save a log and copy it to the local storage
    
this.handleMultiFileData(
         streamProvider,  uploadPath);
    
return Request.CreateResponse(HttpStatusCode.OK);
    }
   
catch (System.Exception ex)
    {
}
}       

private void handleMultiFileData(
   
MultipartFormDataStreamProvider streamProvider,String uploadPath)       
{
  
foreach (MultipartFileData fileData in streamProvider.FileData)
   {
      
String fileName = fileData.Headers.ContentDisposition.FileName;
      
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
       {
           fileName = fileName.Trim(
'"');
       }
      
if (fileName.Contains(@"/") || fileName.Contains(@"\"))
       {
           fileName =
Path.GetFileName(fileName);
       }

      
//Start writing file-data to storage
     
String tagetFilePath = Path.Combine(uploadPath, fileName);
      File.Move(fileData.LocalFileName, tagetFilePath);
   }
}


3.  If you just want a upload service, that’s it. Without SignalR, it still works cool.

沒有留言:

張貼留言