I am trying to use async chunk upload with Web API 2.
But always after first chunk I am receiving message “Cannot read property 'chunkIndex' of undefined”.
What did I do wrong?
using
System;
using
System.IO;
using
System.Runtime.Serialization;
using
System.Runtime.Serialization.Json;
using
System.Text;
using
System.Web;
using
System.Web.Hosting;
using
System.Web.Http;
namespace
UploadWebApi.Controllers
{
public
class
UploadController : ApiController
{
[DataContract]
public
class
ChunkMetaData
{
[DataMember(Name =
"uploadUid"
)]
public
string
UploadUid {
get
;
set
; }
[DataMember(Name =
"fileName"
)]
public
string
FileName {
get
;
set
; }
[DataMember(Name =
"contentType"
)]
public
string
ContentType {
get
;
set
; }
[DataMember(Name =
"chunkIndex"
)]
public
long
ChunkIndex {
get
;
set
; }
[DataMember(Name =
"totalChunks"
)]
public
long
TotalChunks {
get
;
set
; }
[DataMember(Name =
"totalFileSize"
)]
public
long
TotalFileSize {
get
;
set
; }
}
public
class
FileResult
{
public
bool
Uploaded {
get
;
set
; }
public
string
FileUid {
get
;
set
; }
}
public
class
Files
{
public
string
Extension {
get
;
set
; }
public
string
Name {
get
;
set
; }
public
int
Size {
get
;
set
; }
public
string
Uid {
get
;
set
; }
}
public
IHttpActionResult Save(HttpFileCollection files)
{
string
path = String.Empty;
if
(files !=
null
)
{
for
(var i = 0; i < files.Count; i++)
{
path = Path.Combine(HostingEnvironment.MapPath(
"~/App_Data"
), files[i].FileName);
files[i].SaveAs(path);
}
}
return
Ok(
""
);
}
public
IHttpActionResult Remove(
string
[] fileNames)
{
if
(fileNames !=
null
)
{
foreach
(var fullName
in
fileNames)
{
var fileName = Path.GetFileName(fullName);
var physicalPath = Path.Combine(HostingEnvironment.MapPath(
"~/App_Data"
), fileName);
if
(File.Exists(physicalPath))
{
File.Delete(physicalPath);
}
}
}
return
Ok(
""
);
}
public
void
AppendToFile(
string
fullPath, Stream content)
{
try
{
using
(FileStream stream =
new
FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using
(content)
{
content.CopyTo(stream);
}
}
}
catch
(IOException ex)
{
throw
ex;
}
}
public
IHttpActionResult ChunkSave()
{
var files = HttpContext.Current.Request.Files;
var metaData = HttpContext.Current.Request.Form[
"metadata"
];
if
(metaData ==
null
)
{
return
Save(files);
}
MemoryStream ms =
new
MemoryStream(Encoding.UTF8.GetBytes(metaData));
var serializer =
new
DataContractJsonSerializer(
typeof
(ChunkMetaData));
ChunkMetaData somemetaData = serializer.ReadObject(ms)
as
ChunkMetaData;
string
path = String.Empty;
if
(files !=
null
)
{
for
(var i = 0; i < files.Count; i++)
{
path = Path.Combine(HostingEnvironment.MapPath(
"~/App_Data"
), somemetaData.FileName);
AppendToFile(path, files[i].InputStream);
}
}
FileResult fileBlob =
new
FileResult();
fileBlob.Uploaded = somemetaData.TotalChunks - 1 <= somemetaData.ChunkIndex;
fileBlob.FileUid = somemetaData.UploadUid;
return
Json(fileBlob);
}
}
}