Пример #1
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult        result = new UploadResult();
            CustomUploaderInput input  = new CustomUploaderInput(fileName, text);

            if (uploader.RequestFormat == CustomUploaderRequestFormat.MultipartFormData)
            {
                if (string.IsNullOrEmpty(uploader.FileFormName))
                {
                    result.Response = SendRequestMultiPart(uploader.GetRequestURL(input), uploader.GetArguments(input),
                                                           uploader.GetHeaders(input), null, uploader.ResponseType, uploader.RequestType);
                }
                else
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(text);
                    using (MemoryStream stream = new MemoryStream(bytes))
                    {
                        result = SendRequestFile(uploader.GetRequestURL(input), stream, fileName, uploader.GetFileFormName(),
                                                 uploader.GetArguments(input), uploader.GetHeaders(input), null, uploader.ResponseType, uploader.RequestType);
                    }
                }
            }
            else if (uploader.RequestFormat == CustomUploaderRequestFormat.URLQueryString)
            {
                result.Response = SendRequest(uploader.RequestType, uploader.GetRequestURL(input), uploader.GetArguments(input),
                                              uploader.GetHeaders(input), null, uploader.ResponseType);
            }
            else if (uploader.RequestFormat == CustomUploaderRequestFormat.JSON)
            {
                result.Response = SendRequest(uploader.RequestType, uploader.GetRequestURL(input), uploader.GetData(input), UploadHelpers.ContentTypeJSON,
                                              uploader.GetArguments(input), uploader.GetHeaders(input), null, uploader.ResponseType);
            }
            else if (uploader.RequestFormat == CustomUploaderRequestFormat.Binary)
            {
                byte[] bytes = Encoding.UTF8.GetBytes(text);
                using (MemoryStream stream = new MemoryStream(bytes))
                {
                    result.Response = SendRequest(uploader.RequestType, uploader.GetRequestURL(input), stream, UploadHelpers.GetMimeType(fileName),
                                                  uploader.GetArguments(input), uploader.GetHeaders(input), null, uploader.ResponseType);
                }
            }
            else if (uploader.RequestFormat == CustomUploaderRequestFormat.FormURLEncoded)
            {
                result.Response = SendRequestURLEncoded(uploader.RequestType, uploader.GetRequestURL(input), uploader.GetArguments(input),
                                                        uploader.GetHeaders(input), null, uploader.ResponseType);
            }
            else
            {
                throw new Exception("Unsupported request format: " + uploader.RequestFormat);
            }

            try
            {
                uploader.ParseResponse(result, input);
            }
            catch (Exception e)
            {
                Errors.Add(Resources.CustomFileUploader_Upload_Response_parse_failed_ + Environment.NewLine + e);
            }

            return(result);
        }
Пример #2
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            bool isPathStyleRequest = Settings.UsePathStyle;

            if (!isPathStyleRequest && Settings.Bucket.Contains("."))
            {
                isPathStyleRequest = true;
            }

            string endpoint       = URLHelpers.RemovePrefixes(Settings.Endpoint);
            string host           = isPathStyleRequest ? endpoint : $"{Settings.Bucket}.{endpoint}";
            string algorithm      = "AWS4-HMAC-SHA256";
            string credentialDate = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string region         = GetRegion();
            string scope          = URLHelpers.CombineURL(credentialDate, region, "s3", "aws4_request");
            string credential     = URLHelpers.CombineURL(Settings.AccessKeyID, scope);
            string timeStamp      = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string contentType    = UploadHelpers.GetMimeType(fileName);
            string hashedPayload;

            if (Settings.SignedPayload)
            {
                hashedPayload = Helpers.BytesToHex(Helpers.ComputeSHA256(stream));
            }
            else
            {
                hashedPayload = "UNSIGNED-PAYLOAD";
            }

            if ((Settings.RemoveExtensionImage && Helpers.IsImageFile(fileName)) ||
                (Settings.RemoveExtensionText && Helpers.IsTextFile(fileName)) ||
                (Settings.RemoveExtensionVideo && Helpers.IsVideoFile(fileName)))
            {
                fileName = Path.GetFileNameWithoutExtension(fileName);
            }

            string uploadPath = GetUploadPath(fileName);

            NameValueCollection headers = new NameValueCollection
            {
                ["Host"]                 = host,
                ["Content-Length"]       = stream.Length.ToString(),
                ["Content-Type"]         = contentType,
                ["x-amz-date"]           = timeStamp,
                ["x-amz-content-sha256"] = hashedPayload,
                ["x-amz-storage-class"]  = Settings.StorageClass.ToString()
            };

            if (Settings.SetPublicACL)
            {
                headers["x-amz-acl"] = "public-read";
            }

            string canonicalURI = uploadPath;

            if (isPathStyleRequest)
            {
                canonicalURI = URLHelpers.CombineURL(Settings.Bucket, canonicalURI);
            }
            canonicalURI = URLHelpers.AddSlash(canonicalURI, SlashType.Prefix);
            canonicalURI = URLHelpers.URLEncode(canonicalURI, true);
            string canonicalQueryString = "";
            string canonicalHeaders     = CreateCanonicalHeaders(headers);
            string signedHeaders        = GetSignedHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      hashedPayload;

            string stringToSign = algorithm + "\n" +
                                  timeStamp + "\n" +
                                  scope + "\n" +
                                  Helpers.BytesToHex(Helpers.ComputeSHA256(canonicalRequest));

            byte[] dateKey              = Helpers.ComputeHMACSHA256(credentialDate, "AWS4" + Settings.SecretAccessKey);
            byte[] dateRegionKey        = Helpers.ComputeHMACSHA256(region, dateKey);
            byte[] dateRegionServiceKey = Helpers.ComputeHMACSHA256("s3", dateRegionKey);
            byte[] signingKey           = Helpers.ComputeHMACSHA256("aws4_request", dateRegionServiceKey);

            string signature = Helpers.BytesToHex(Helpers.ComputeHMACSHA256(stringToSign, signingKey));

            headers["Authorization"] = algorithm + " " +
                                       "Credential=" + credential + "," +
                                       "SignedHeaders=" + signedHeaders + "," +
                                       "Signature=" + signature;

            headers.Remove("Host");
            headers.Remove("Content-Type");

            string url = URLHelpers.CombineURL(host, canonicalURI);

            url = URLHelpers.ForcePrefix(url, "https://");

            using (HttpWebResponse response = GetResponse(HttpMethod.PUT, url, stream, contentType, null, headers))
            {
                if (response != null)
                {
                    NameValueCollection responseHeaders = response.Headers;

                    if (responseHeaders != null && responseHeaders["ETag"] != null)
                    {
                        return(new UploadResult
                        {
                            IsSuccess = true,
                            URL = GenerateURL(uploadPath)
                        });
                    }
                }
            }

            Errors.Add("Upload to Amazon S3 failed.");
            return(null);
        }
Пример #3
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            UploadResult        result = new UploadResult();
            CustomUploaderInput input  = new CustomUploaderInput(fileName, "");

            if (uploader.Body == CustomUploaderBody.MultipartFormData)
            {
                result = SendRequestFile(uploader.GetRequestURL(input), stream, fileName, uploader.GetFileFormName(), uploader.GetArguments(input),
                                         uploader.GetHeaders(input), null, uploader.RequestMethod);
            }
            else if (uploader.Body == CustomUploaderBody.Binary)
            {
                result.Response = SendRequest(uploader.RequestMethod, uploader.GetRequestURL(input), stream, UploadHelpers.GetMimeType(fileName), null,
                                              uploader.GetHeaders(input));
            }
            else
            {
                throw new Exception("Unsupported request format: " + uploader.Body);
            }

            try
            {
                uploader.ParseResponse(result, LastResponseInfo, input);
            }
            catch (Exception e)
            {
                Errors.Add(Resources.CustomFileUploader_Upload_Response_parse_failed_ + Environment.NewLine + e);
            }

            return(result);
        }
Пример #4
0
        protected void UploadFile(FileUpload fuBulkUpload, string _filename)
        {
            // Delay for Progress Bar
            Thread.Sleep(5000);

            #region Add Item Programmatically
            DirectoryInfo dir = null;
            string        extension, fileName = string.Empty;
            string        path      = string.Empty;
            string        tableName = string.Empty;
            string        getError  = string.Empty;
            DataSet       dataSet   = new DataSet();
            try
            {
                if (fuBulkUpload.HasFile)
                {
                    string folderName = Guid.NewGuid().ToString();

                    string        folderpath        = Server.MapPath("~/sitecore/admin/template/" + folderName + "/");
                    string[]      templatePathFiles = Directory.GetFiles(Server.MapPath("~/sitecore/admin/template/"), "*.xml", SearchOption.TopDirectoryOnly);
                    List <string> templateFiles     = new List <string>();
                    foreach (string template in templatePathFiles)
                    {
                        templateFiles.Add(Path.GetFileName(template).Substring(0, Path.GetFileName(template).LastIndexOf(".")));
                    }
                    ServerMapPath = folderpath;
                    dir           = Directory.CreateDirectory(folderpath);
                    extension     = Path.GetExtension(fuBulkUpload.FileName);
                    fileName      = fuBulkUpload.FileName.Substring(0, fuBulkUpload.FileName.LastIndexOf('.'));
                    //if (fuBulkUpload.PostedFile.ContentLength > (maxFile * 1024))
                    //    throw new Exception(string.Format("File size more than {0}MB, please upload file less than {1}MB.", maxFile, maxFile));
                    if (extension != ".csv")
                    {
                        throw new FormatException("Wrong File Format.");
                    }
                    if (_filename != fileName)
                    {
                        throw new Exception("Wrong File Upload. File Upload using filename " + _filename + ".csv or Try another File Upload..");
                    }
                    if (!templateFiles.Contains(fileName))
                    {
                        throw new Exception("Wrong File Name. No template name equals with this file name");
                    }
                    path = folderpath + fuBulkUpload.FileName;
                    fuBulkUpload.SaveAs(path);

                    Data = LibraryHelpers.ConvertCSVToTable(path);
                    UploadHelpers.MappedDataToDB(Data, folderpath.Replace(folderName, "") + "/" + fileName + ".xml", fileName);
                    getError = UploadHelpers.GetErrorMessage();

                    if (getError == "ERROR")
                    {
                        litWarningError.Text = "Database is not Updated. Please make sure the Data is Valid.";
                        Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertWarning", "AlertWarningBottom()", true);
                    }
                    else
                    {
                        fuBulkUpload.Dispose();
                        Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertSuccess", "AlertSuccessBottom()", true);
                    }

                    File.Delete(path);
                }
            }
            catch (FormatException fx)
            {
                litAlertError.Text = fx.Message;
                Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertFailed", "AlertFailedBottom()", true);
            }
            catch (Exception ex)
            {
                litAlertError.Text = " " + ex.Message;
                Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertFailed", "AlertFailedBottom()", true);
            }
            finally
            {
                if (!string.IsNullOrEmpty(path))
                {
                    File.Delete(path);
                }
                dir.Delete();
            }
            #endregion
        }