WebApi实现多文件上传
2017-03-27 本文已影响855人
Bobby0322
WebApi实现多文件上传
Api
#region UploadScanPage
/// <summary>
/// Post
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("api/scn/UploadScanPage")]
[ResponseType(typeof(Resource))]
public async Task<IHttpActionResult> Post()
{
var resources = new List<Resource>();
// multipart/form-data
// 采用MultipartMemoryStreamProvider
var provider = new MultipartMemoryStreamProvider();
// 读取文件数据
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var item in provider.Contents)
{
// 判断是否是文件
if (item.Headers.ContentDisposition.FileName == null) continue;
// 获取到流
var ms = item.ReadAsStreamAsync().Result;
// 进行流操作
using (var br = new BinaryReader(ms))
{
if (ms.Length <= 0)
break;
// 读取文件内容到内存中
var data = br.ReadBytes((int) ms.Length);
/*
// Create
// 当前时间作为ID
var resource = new Resource()
{
Id = DateTime.Now.ToString("yyyyMMddHHmmssffff", DateTimeFormatInfo.InvariantInfo)
};
*/
// Info
var info = new FileInfo(item.Headers.ContentDisposition.FileName.Replace("\"", ""));
var resource = new Resource
{
Id = info.Name,
Type = info.Extension.Substring(1).ToLower()
};
// 文件类型
// Write
try
{
// 文件存储地址
var dirPath = Path.Combine(RootPath);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
File.WriteAllBytes(Path.Combine(dirPath, resource.Id), data);
resources.Add(resource);
}
catch
{
// ignored
}
}
}
// 返回
switch (resources.Count)
{
case 0:
return BadRequest();
case 1:
return Ok(resources.FirstOrDefault());
default:
return Ok(resources);
}
}
#endregion
Resource
public class Resource
{
public string Id { get; set; }
public string Type { get; set; }
}
UpLoadFileTest
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace UpLoadFileTest
{
public class UpLoadFileTest
{
/// <summary>
/// BatchUpLoadFiles
/// </summary>
/// <param name="baseAddress"></param>
/// <param name="postUrl"></param>
/// <param name="imagesPath"></param>
/// <param name="files"></param>
public void BatchUpLoadFiles(string baseAddress, string postUrl
,string imagesPath, List<string> files)
{
/*
* 批量上传图片
* baseAddress: "http://localhost:7427/"
* postUrl: "/api/scn/UploadScanPage"
* imagesPath: "e:\10001003\"
* filePath: "e:\10001003\1.jpg"
*/
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
// Make sure to change API address
client.BaseAddress = new Uri(baseAddress);
var count = 1;
foreach (var imageName in files)
{
// Add file content
var filePath = imagesPath + imageName;
var fileContent = new ByteArrayContent(File.ReadAllBytes(@filePath));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = imageName
};
content.Add(fileContent);
Console.WriteLine((count++) + "/" + files.Count);
}
// Make a call to Web API
var result = client.PostAsync(postUrl, content).Result;
Console.WriteLine(result.StatusCode);
Console.ReadLine();
}
}
}
}
}
Program
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace UpLoadFileTest
{
class Program
{
static void Main(string[] args)
{
var baseAddress = "http://localhost:7427/";
var postUrl = "/api/scn/UploadScanPage";
var imagesPath = @"e:\10001003\";
var files = new List<string> {"1.jpg", "2.jpg"};
new UpLoadFileTest().BatchUpLoadFiles(baseAddress, postUrl, imagesPath, files);
}
}
}