验证上传的文件是C#restful webservice中的excel电子表格

时间:2017-07-06 13:26:20

标签: c# asp.net excel validation

我正在尝试验证通过多部分表单数据上传的文件实际上是一个Excel电子表格。

我的HTML将文件类型限制为xlsxlsx

<input type="file" id="filePicker" accept=".xls,.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"/>

但我想真正验证该文件实际上是一个excel文档,并在服务器上验证它。我一直在寻找并且似乎找不到不使用ASP.NET FileUpload Control的解决方案。

这是我用来读取多部分表单数据并将文件写入服务器上的磁盘的C#。这是我希望进行验证的地方。

[Route("ImportFile", Name = "ImportSPVFiles")]
[HttpPost]
public async Task<HttpResponseMessage> ImportFiles()
{
    if (Request.Content.IsMimeMultipartContent())
    {
        Stream data = await Request.Content.ReadAsStreamAsync();

        var parser = new MultipartFormDataParser(data);

        byte[] buffer = new byte[16 * 1024];

        foreach (var file in parser.Files)
        {
            if (string.IsNullOrEmpty(file.FileName))
            {
                return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
            }
            string fileName = file.FileName;
            if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
            {
                fileName = fileName.Trim('"');
            }
            if (fileName.Contains(@"/") || fileName.Contains(@"\"))
            {
                fileName = Path.GetFileName(fileName);
            }
            Stream fileData = file.Data;

            BufferedStream bStream = new BufferedStream(fileData);
            if(File.Exists(StoragePath + "\\" + file.FileName)){
                File.Delete(StoragePath + "\\" + file.FileName);
            }
            using (var fileStream = File.Create(StoragePath + "\\" + file.FileName)){
                bStream.CopyTo(fileStream);
           }

           fileQueue.Send(file.FileName);
       }

       return Request.CreateResponse(HttpStatusCode.OK,"Request was sent and being queued for processing");
       }
    else
    {
        return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
    }
}

提前致谢。

0 个答案:

没有答案