Ejemplo n.º 1
0
        /// <summary>
        /// 保存附件信息到数据库
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="folder">保存文件夹</param>
        /// <returns></returns>
        private Attachment SaveAttchment(PoseidonMultipartFormDataStreamProvider provider, string folder)
        {
            MultipartFileData file = provider.FileData[0];

            Attachment attachment = new Attachment();

            attachment.FileName    = Path.GetFileName(file.LocalFileName);
            attachment.OriginName  = file.Headers.ContentDisposition.FileName;
            attachment.Extension   = Path.GetExtension(file.LocalFileName);
            attachment.ContentType = file.Headers.ContentType.MediaType;
            attachment.UploadTime  = DateTime.Now;
            attachment.Size        = new FileInfo(file.LocalFileName).Length;
            attachment.Folder      = folder;
            attachment.MD5Hash     = Hasher.GetFileMD5Hash(file.LocalFileName);

            if (file.Headers.Contains("md5hash"))
            {
                string md5 = file.Headers.GetValues("md5hash").ToList().First();

                if (attachment.MD5Hash != md5)
                {
                    throw new Exception("文件哈希计算不匹配");
                }
            }

            attachment.Name   = provider.FormData["name"];
            attachment.Remark = provider.FormData["remark"];

            BusinessFactory <AttachmentBusiness> .Instance.Create(attachment);

            return(attachment);
        }
Ejemplo n.º 2
0
        public async Task <HttpResponseMessage> PostFileDataAsync()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root   = AppConfig.GetAppSetting("UploadPath");
            var    folder = GeneratePath();

            var path = HttpContext.Current.Server.MapPath("~" + root + "//" + folder);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var provider = new PoseidonMultipartFormDataStreamProvider(path);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                if (provider.FileData.Count == 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.Forbidden));
                }

                var attachment = SaveAttchment(provider, folder);

                return(Request.CreateResponse(HttpStatusCode.OK, attachment));
            }
            catch (System.Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }