예제 #1
0
        public async Task <ServiceResult> PostFile(string UUID, string type)
        //public ServiceResult PostFile(string UUID, string type)
        {
            var fileResult = new FileEx();

            fileResult.Default = false;
            string pathToImage = "";
            string root        = "";

            string basePath = "/Content/Uploads/" + this.CurrentUser.UUID;

            if (type.EqualsIgnoreCase("user") || type.EqualsIgnoreCase("profile") || type.EqualsIgnoreCase("profilemember"))
            {
                basePath = "/Content/Protected/" + this.CurrentUser.UUID;
            }

            try
            {
                if (this.CurrentUser == null)
                {
                    return(ServiceResponse.Error("You must be logged in to upload."));
                }

                #region non async

                //var httpRequest = HttpContext.Current.Request;
                //if (httpRequest.Files.Count < 1)
                //{
                //    return ServiceResponse.Error("Bad request");
                //}

                //foreach (string file in httpRequest.Files)
                //{
                //    var postedFile = httpRequest.Files[file];
                //    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                //    postedFile.SaveAs(filePath);

                //}

                //return ServiceResponse.OK();

                #endregion non async

                HttpRequestMessage request = this.Request;
                if (!request.Content.IsMimeMultipartContent())
                {
                    return(ServiceResponse.Error("Unsupported media type."));
                }

                root = System.Web.HttpContext.Current.Server.MapPath("~" + basePath);

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

                var provider = new MultipartFormDataStreamProvider(root);

                //  foreach (MultipartFileData file in provider.FileData)
                //{
                //    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                //    Trace.WriteLine("Server file path: " + file.LocalFileName);

                //    //AppManager app = new AppManager(Globals.DBConnectionKey, "web", this.GetAuthToken(Request));
                //    //string fileName = file.Headers.ContentDisposition.FileName;

                //    //// Clean the file name..
                //    //foreach (var c in Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, ' '); }

                //    //if (string.IsNullOrWhiteSpace(fileName))
                //    //    continue;

                //    //fileName = fileName.ToUpper();

                //}
                //return ServiceResponse.OK();

                ServiceResult res = await request.Content.ReadAsMultipartAsync(provider).
                                    ContinueWith <ServiceResult>(o =>
                {
                    if (o.IsFaulted || o.IsCanceled)
                    {
                        _logger.InsertError("o.IsFaulted:" + o.IsFaulted, "AttributesController", "PostFile");
                        _logger.InsertError("o.IsCanceled:" + o.IsCanceled, "AttributesController", "PostFile");
                        _logger.InsertError("o.Exception:" + JsonConvert.SerializeObject(o), "AttributesController", "PostFile");

                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    }
                    string fileName   = "";
                    List <string> kvp = o.Result.Contents.First().Headers.First(w => w.Key == "Content-Disposition").Value.ToList()[0].Split(';').ToList();
                    foreach (string value in kvp)
                    {
                        if (value.Trim().StartsWith("filename"))
                        {
                            String[] tmp = value.Split('=');
                            fileName     = DateTime.UtcNow.ToString("yyyyMMdd_hhmmss") + tmp[1].Trim().Replace("\"", "");
                        }

                        if (value.Contains("defaultImage"))        //value.Trim().StartsWith("name"))
                        {
                            fileResult.Default = true;
                        }
                    }
                    // this is the file name on the server where the file was saved
                    string file             = provider.FileData.First().LocalFileName;
                    string originalFilename = Path.GetFileName(file);
                    string destFile         = file.Replace(originalFilename, fileName);
                    try
                    {
                        if (File.Exists(destFile))
                        {
                            File.Delete(destFile);
                        }
                    }
                    catch
                    {     //file may still be locked so don't worry about it.
                    }

                    try
                    {
                        string extension = Path.GetExtension(destFile)?.ToUpper();
                        if (!string.IsNullOrWhiteSpace(extension))
                        {
                            extension = extension.Replace(".", "");
                        }

                        var image = System.Drawing.Image.FromFile(file);
                        using (var resized = ImageEx.ResizeImage(image, 640, 640))
                        {
                            switch (extension)
                            {
                            case "PNG":
                                resized.Save(destFile, ImageFormat.Png);
                                break;

                            case "GIF":
                                resized.Save(destFile, ImageFormat.Gif);
                                break;

                            case "JPEG":
                            case "JPG":
                                resized.Save(destFile, ImageFormat.Jpeg);
                                break;

                            default:
                                ImageEx.SaveJpeg(destFile, resized, 90);
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.Assert(false, ex.Message);
                    }

                    //try
                    //{
                    //    File.Move(file, destFile);
                    //}
                    //catch { }//ditto from above catch

                    file = destFile;

                    string thumbFile = ImageEx.CreateThumbnailImage(file, 64);
                    string ImageUrl  = fileName;
                    string fullUrl   = this.Request.RequestUri.Scheme + "://" + this.Request.RequestUri.Authority + basePath + "/"; // "/Content/Uploads/" + this.CurrentUser.UUID + "/";
                    pathToImage      = fullUrl + thumbFile;                                                                         // ImageUrl;

                    if (fileResult.Default)
                    {
                        this.UpdateImageURL(UUID, type, pathToImage);    //Now update the database.
                    }
                    else
                    {
                        //add other images to attributes

                        AttributeManager atm = new AttributeManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

                        var attribute = new TMG.Attribute()
                        {
                            ReferenceUUID = UUID,
                            ReferenceType = type,
                            Value         = thumbFile,
                            Image         = thumbFile,
                            ValueType     = "ImagePath",
                            Name          = fileResult.Name,
                            AccountUUID   = this.CurrentUser.AccountUUID,
                            DateCreated   = DateTime.UtcNow,
                            CreatedBy     = CurrentUser.UUID,
                            RoleOperation = ">=",
                            RoleWeight    = RoleFlags.MemberRoleWeights.Member,
                            Private       = false,
                            NSFW          = -1
                        };
                        atm.Insert(attribute);
                    }

                    fileResult.UUID       = UUID;
                    fileResult.UUIDType   = type;
                    fileResult.Status     = "saved";
                    fileResult.Image      = fullUrl + ImageUrl;
                    fileResult.ImageThumb = fullUrl + ImageEx.GetThumbFileName(destFile);     //todo check this
                    fileResult.Name       = fileName;

                    return(ServiceResponse.OK(fileName + " uploaded.", fileResult));
                }
                                                                 );

                return(res);
            }
            catch (Exception ex)
            {
                _logger.InsertError("root folder:" + root, "AttributesController", "PostFile");
                _logger.InsertError(ex.DeserializeException(false), "AttributesController", "PostFile");
                return(ServiceResponse.Error("Upload failed."));
            }
        }