最近做一个csv文件上传,网上找了几个,兼容性不好,年代也比较久远,就去github上看看找找,发现了一个resumable.js,支持分片上传,多文件上传,完全满足需求~项目地址:https://github.com/23/resumable.js。
简单说下应用,顺便保存下代码,万一哪天再用了,忘了还得重新找.....这才是关键。
后台代码,两个文件,一个model,一个webapi,基于C#的。
model代码:
namespace Resumable.Models
{
public class ResumableConfiguration
{
/// <summary>
/// Gets or sets number of expected chunks in this upload.
/// </summary>
public int Chunks { get; set; }
/// <summary>
/// Gets or sets unique identifier for current upload.
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// Gets or sets file name.
/// </summary>
public string FileName { get; set; }
public ResumableConfiguration()
{
}
/// <summary>
/// Creates an object with file upload configuration.
/// </summary>
/// <param name="identifier">Upload unique identifier.</param>
/// <param name="filename">File name.</param>
/// <param name="chunks">Number of file chunks.</param>
/// <returns>File upload configuration.</returns>
public static ResumableConfiguration Create(string identifier, string filename, int chunks)
{
return new ResumableConfiguration { Identifier = identifier, FileName = filename, Chunks = chunks };
}
}
}
API代码:
using Resumable.Models;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace Resumable.Controllers
{
[RoutePrefix("api/File")]
public class FileUploadController : ApiController
{
private string root = System.Web.Hosting.HostingEnvironment.MapPath("~/upload");
[Route("Upload"), HttpOptions]
public object UploadFileOptions()
{
return Request.CreateResponse(HttpStatusCode.OK);
}
[Route("Upload"), HttpGet]
public object Upload(int resumableChunkNumber, string resumableIdentifier)
{
return ChunkIsHere(resumableChunkNumber, resumableIdentifier) ? Request.CreateResponse(HttpStatusCode.OK) : Request.CreateResponse(HttpStatusCode.NoContent);
}
[Route("Upload"), HttpPost]
public async Task<object> Upload()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
if (!Directory.Exists(root)) Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
if (await readPart(provider))
{
// Success
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
// Fail
var message = DeleteInvalidChunkData(provider) ? "Cannot read multi part file data." : "Cannot delete temporary file chunk data.";
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new System.Exception(message));
}
}
private static bool DeleteIn