Inheritance: IHttpHandler
Example #1
0
        /// <summary>
        /// The core logic that sends the request.
        /// It has to send the request but do nothing to the response.
        /// </summary>
        internal static IEnumerator TheRequestCoroutine(
            string method,
            string url,
            Dictionary <string, string> headers,
            JsonObject payload,
            Action <UnityWebRequest, DownloadHandlerBuffer> callback
            )
        {
            // TODO: enforce SSL certificates

            var downloadHandler = new DownloadHandlerBuffer();

            UploadHandler uploadHandler = null;

            if (payload != null)
            {
                uploadHandler = new UploadHandlerRaw(
                    Encoding.UTF8.GetBytes(payload.ToString())
                    );
            }

            var request = new UnityWebRequest(
                url,
                method,
                downloadHandler,
                uploadHandler
                );

            if (headers != null)
            {
                foreach (var pair in headers)
                {
                    request.SetRequestHeader(pair.Key, pair.Value);
                }
            }

            if (payload != null)
            {
                request.SetRequestHeader("Accept", "application/json");
                request.SetRequestHeader("Content-Type", "application/json");
            }

            yield return(request.SendWebRequest());

            callback?.Invoke(request, downloadHandler);
        }
Example #2
0
 public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
                      UUID parentFolderID, string invType, string assetType, string path,
                      uint everyoneMask, uint groupMask, uint nextOwnerMask, UploadHandler action)
 {
     m_assetName             = assetName;
     m_assetDes              = description;
     newAssetID              = assetID;
     inventoryItemID         = inventoryItem;
     uploaderPath            = path;
     parentFolder            = parentFolderID;
     m_assetType             = assetType;
     m_invType               = invType;
     m_everyone_mask         = everyoneMask;
     m_group_mask            = groupMask;
     m_next_owner_mask       = nextOwnerMask;
     m_uploadCompleteHandler = action;
 }
Example #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                upload_handler = new UploadHandler(Server.MapPath("."), FullUrlGet());
                Response.Clear();
                Response.AddHeader("Pragma", "no-cache");
                Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
                Response.AddHeader("X-Content-Type-Options", "nosniff");
                Response.AddHeader("Access-Control-Allow-Origin", "*");
                Response.AddHeader("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE");
                Response.AddHeader("Access-Control-Allow-Headers", "X-File-Name, X-File-Type, X-File-Size");

                switch (Request.HttpMethod)
                {
                    case "OPTIONS":
                        break;
                    case "HEAD":
                    case "GET":
                        Get();
                        break;
                    case "POST":
                        if (Request["file"] != null)
                        {
                            Delete();
                        }
                        else
                        {
                            Post();
                        }
                        break;
                    case "DELETE":
                        Delete();
                        break;
                    default: //Delete();
                        Response.Status = "Method Not Allowed";
                        Response.StatusCode = 405;
                        Response.End();
                        break;
                }
            }catch(Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
Example #4
0
        public void Status_Exception_Should_Provide_Expiration_Event_Id()
        {
            SystemTime.Now = () => Token.ExpirationTime.Value.AddSeconds(1);

            //make sure the scheduler can readjust
            Thread.CurrentThread.Join(500);

            try
            {
                var block = CreateBufferedBlocks().First();
                UploadHandler.WriteBlock(block);
                Assert.Fail("Expected status exception due to expiration.");
            }
            catch (TransferStatusException expected)
            {
                Assert.AreEqual((int)AuditEvent.UploadNoLongerActive, expected.EventId);
            }
        }
        public void Submitting_Last_Block_Should_Automatically_Close_Transfer()
        {
            var blocks = CreateBufferedBlocks();
            var block  = blocks[20];

            block.IsLastBlock = true;
            blocks.Remove(block);

            //write all blocks in the list
            blocks.Do(UploadHandler.WriteBlock);
            Assert.AreEqual(TransferStatus.Running, UploadHandler.GetTransferStatus(Token.TransferId));

            //write last block
            UploadHandler.WriteBlock(block);
            Assert.AreEqual(TransferStatus.Completed, UploadHandler.GetTransferStatus(Token.TransferId));

            FileAssert.AreEqual(SourceFile, TargetFile);
        }
        public void Transfer_Should_Be_Denied_If_Upload_Is_Already_Running()
        {
            try
            {
                Token = UploadHandler.RequestUploadToken(TargetFilePath, true, 5000, "");
                Assert.Fail("Got upload token while download is running.");
            }
            catch (ResourceLockedException expected)
            {
            }
            finally
            {
                UploadHandler.CancelTransfer(Token.TransferId, AbortReason.ClientAbort);
            }

            //after the canceling, it should work
            InitToken();
        }
Example #7
0
        public void Pausing_And_Resuming_Transfer_Should_Update_Reported_Transfer_Status()
        {
            List <BufferedDataBlock> blocks = CreateBufferedBlocks();

            foreach (var block in blocks)
            {
                UploadHandler.PauseTransfer(Token.TransferId);
                Assert.AreEqual(TransferStatus.Paused, UploadHandler.GetTransferStatus(Token.TransferId));

                UploadHandler.WriteBlock(block);

                Assert.AreEqual(TransferStatus.Running, UploadHandler.GetTransferStatus(Token.TransferId));
            }

            //complete and recompare
            UploadHandler.CompleteTransfer(Token.TransferId);
            FileAssert.AreEqual(SourceFile, TargetFile);
        }
        /// <summary>
        /// Method to Open a file dialog which can take a pdf or image file and upload it to the database.
        /// </summary>
        private void OpenFileDialog()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            fileDialog.Filter           = "Files(*.BMP;*.JPG;*.JPEG;*.PDF)|*.BMP;*.JPG;*.JPEG;*.PDF";

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                IUploadHandler uploader = new UploadHandler();

                if (fileDialog.CheckFileExists)
                {
                    if (_documentType == Session.TypeFirstAid)
                    {
                        if (uploader.UploadFirstAid(_documentName, fileDialog.FileName,
                                                    Properties.Settings.Default["DocumentUpload"].ToString()))
                        {
                            LoadFirstAid(Session.LoggedInUser);
                        }
                        else
                        {
                            CustomMsgBox.ShowOk("Unable to upload document", "Error", CustomMsgBoxIcon.Error);
                        }
                    }
                    else if (_documentType == Session.TypeDoctorsNote)
                    {
                        if (uploader.UploadDoctorsNote(_documentName, fileDialog.FileName,
                                                       Properties.Settings.Default["DocumentUpload"].ToString()))
                        {
                            LoadDoctorsNote(Session.LoggedInUser);
                        }
                        else
                        {
                            CustomMsgBox.ShowOk("Unable to upload document", "Error", CustomMsgBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    CustomMsgBox.ShowOk("File does not exist", "Warrning!", CustomMsgBoxIcon.Warrning);
                }
            }
        }
        public void Writing_A_Single_Empty_Block_Should_Create_File()
        {
            UploadHandler.CancelTransfer(Token.TransferId, AbortReason.ClientAbort);

            //get token for empty file
            Token = UploadHandler.RequestUploadToken(TargetFilePath, false, 0, "");

            TargetFile.Refresh();
            Assert.IsFalse(TargetFile.Exists);

            var block = new BufferedDataBlock {
                TransferTokenId = Token.TransferId, BlockLength = 0, BlockNumber = 0, Data = new byte[0], IsLastBlock = true
            };

            UploadHandler.WriteBlock(block);

            TargetFile.Refresh();
            Assert.IsTrue(TargetFile.Exists);
        }
Example #10
0
 public static Coroutine Request(string param, string method             = UnityWebRequest.kHttpVerbGET,
                                 Action <UnityWebRequest> requestAction  = null,
                                 Action <ErrorLevel, string> errorAction = null,
                                 DownloadHandler downloadHandler         = null,
                                 UploadHandler uploadHandler             = null,
                                 string contentType = "application/json",
                                 bool needAuthorize = false,
                                 bool saveCookie    = false)
 {
     return(current.StartCoroutine(current.RequestAsync(param,
                                                        method,
                                                        requestAction,
                                                        errorAction,
                                                        downloadHandler,
                                                        uploadHandler,
                                                        contentType,
                                                        needAuthorize,
                                                        saveCookie)));
 }
    public static bool PostRequest(string url, WWWForm form, UploadHandler uploadHandler, Dictionary <string, string> headers, Action <string> onSuccess)
    {
        using (UnityWebRequest r = UnityWebRequest.Post(url, form))
        {
            if (uploadHandler != null)
            {
                r.uploadHandler = uploadHandler;
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    r.SetRequestHeader(header.Key, header.Value);
                }
            }

            return(SendPostRequest(r, onSuccess));
        }
    }
        public void Retransmitted_Blocks_Should_Replace_Entries_In_Transferred_Block_Table()
        {
            var block = CreateBufferedBlocks()[10];

            //modify data in one of the blocks
            int blockLength = block.BlockLength.Value / 2;

            block.BlockLength = blockLength;
            block.Data        = block.Data.CreateCopy(blockLength);

            //write block
            UploadHandler.WriteBlock(block);

            //check block
            var blocks = UploadHandler.GetTransferredBlocks(Token.TransferId);

            Assert.AreEqual(1, blocks.Count());
            Assert.AreEqual(blockLength, blocks.Single().BlockLength);

            UploadHandler.PauseTransfer(Token.TransferId);
            TargetFile.Refresh();
            Assert.AreEqual(block.Offset + blockLength, TargetFile.Length);

            //get unmodified block and write that one
            block = CreateBufferedBlocks()[10];
            UploadHandler.WriteBlock(block);

            blocks = UploadHandler.GetTransferredBlocks(Token.TransferId);
            Assert.AreEqual(1, blocks.Count());
            Assert.AreNotEqual(blockLength, blocks.Single().BlockLength);
            Assert.AreEqual(block.BlockLength, blocks.Single().BlockLength);

            UploadHandler.PauseTransfer(Token.TransferId);
            TargetFile.Refresh();
            Assert.AreEqual(block.Offset + block.BlockLength, TargetFile.Length);

            UploadHandler.CompleteTransfer(Token.TransferId);
        }
        public void Unordered_Writing_Should_Be_Supported()
        {
            var blocks = new Dictionary <long, BufferedDataBlock>();

            Random r    = new Random();
            var    list = CreateBufferedBlocks();

            var count = list.Count;

            for (int i = 0; i < count; i++)
            {
                int index = r.Next(list.Count);
                var block = list[index];
                blocks.Add(block.BlockNumber, block);

                UploadHandler.WriteBlock(list[index]);
                list.RemoveAt(index);
            }

            UploadHandler.CompleteTransfer(Token.TransferId);
            TargetFile.Refresh();
            FileAssert.AreEqual(SourceFile, TargetFile);
        }
Example #14
0
        public void Starting_To_Write_After_Expiration_Should_Not_Open_The_Stream()
        {
            SystemTime.Now = () => Token.ExpirationTime.Value.AddSeconds(1);

            //make sure the scheduler can readjust
            Thread.CurrentThread.Join(500);

            //write a block in order to open the stream
            try
            {
                var block = CreateBufferedBlocks().First();
                UploadHandler.WriteBlock(block);
                Assert.Fail("Expected status exception");
            }
            catch (TransferStatusException ignored)
            { }

            //getting an exclusive stream only works if the file was released
            using (var fs = TargetFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                fs.Close();
            }
        }
Example #15
0
        public static async Task <Guid> RunOrchestrator(
            [OrchestrationTrigger] IDurableOrchestrationContext context)
        {
            (var userId, var rawGpxData) = context.GetInput <(Guid, string)>();
            var parsedGpx = GpxParser.Parse(new StringReader(rawGpxData));

            // todo - also upload the file to raw storage!
            // todo - and record the raw file location in the uploaded cache function below.

            var config         = SettingsManager.GetCredentials(); // todo this doesn't work. probably just move these configs for Azure Fxn
            var cosmosWriter   = new UploadHandler(config.EndPoint, config.AuthKey, config.CosmosDatabase, config.CosmosContainer, config.StaticDataCosmosContainer);
            var tripHandler    = new TripProcessorHandler(cosmosWriter);
            var plusCodeRanges = TripProcessorHandler.GetPlusCodeRanges(parsedGpx);

            tripHandler = await context.CallActivityAsync <TripProcessorHandler>("GpxFileUpload_WarmCache", (parsedGpx, tripHandler));

            // parallel tracks: upload raw while also computing overlaps.
            var overlapComputeParams = (parsedGpx, userId, plusCodeRanges, tripHandler);
            var overlappingNodesTask = context.CallActivityAsync <HashSet <UserNodeCoverage> >("GpxFileUpload_OverlappingNodes", overlapComputeParams);

            var uploadRawTask = context.CallActivityAsync("GpxFileUpload_UploadRawRun", (parsedGpx, userId, tripHandler));

            Task.WaitAll(overlappingNodesTask, uploadRawTask);
            var overlappingNodes = overlappingNodesTask.Result;

            // upload overlapping nodes
            var uploadCacheTask       = context.CallActivityAsync("GpxFileUpload_UploadCache", (overlappingNodes, tripHandler));
            var updateUserWayCoverage = context.CallActivityAsync("GpxFileUpload_UpdateUserWayCoverage", (overlappingNodes, userId, plusCodeRanges, tripHandler));

            Task.WaitAll(uploadCacheTask, updateUserWayCoverage);

            // upload summary
            await context.CallActivityAsync("GpxFileUpload_UpdateUserSummaryAsync", (userId, tripHandler));

            return(userId);
        }
        public void Uploading_An_Empty_File_Should_Create_The_File()
        {
            UploadHandler.CancelTransfer(Token.TransferId, AbortReason.ClientAbort);

            SourceFile.Delete();
            using (var fs = SourceFile.Create())
            {
                fs.Close();
            }

            SourceFile.Refresh();
            Assert.AreEqual(0, SourceFile.Length);

            TargetFile.Refresh();
            Assert.IsFalse(TargetFile.Exists);

            using (var fs = SourceFile.OpenRead())
            {
                UploadHandler.WriteFile(TargetFilePath, fs, true, 0, "");
            }

            TargetFile.Refresh();
            Assert.IsTrue(TargetFile.Exists);
        }
Example #17
0
        private static string GetUploadStringPresent(UploadHandler uploadHandler)
        {
            if (uploadHandler == null)
            {
                return("upload handler in undefined");
            }

            switch (uploadHandler.contentType)
            {
            case "application/json":
            case "text/plain":
            case "text/xml":
            case "text/markdown":
            case "message/http":
            case "message/imdn+xml":
            case "application/xml":
            case "application/xop+xml":
            case "application/xml-dtd":
                return($"{uploadHandler.contentType}:\n" +
                       $"{Encoding.UTF8.GetString(uploadHandler.data)}");

            default: return($"{uploadHandler.contentType}: <RAW DATA>");
            }
        }
        public void Retransmitted_Blocks_Should_Overwrite_Previously_Transferred_Data()
        {
            List <BufferedDataBlock> blocks = CreateBufferedBlocks();

            //modify data in one of the blocks
            Array.Reverse(blocks[10].Data);

            foreach (var block in blocks)
            {
                UploadHandler.WriteBlock(block);
            }

            //pause in order to release stream
            UploadHandler.PauseTransfer(Token.TransferId);
            FileAssert.AreNotEqual(SourceFile, TargetFile);

            //write correct block data
            blocks = CreateBufferedBlocks();
            UploadHandler.WriteBlock(blocks[10]);

            //complete and recompare
            UploadHandler.CompleteTransfer(Token.TransferId);
            FileAssert.AreEqual(SourceFile, TargetFile);
        }
Example #19
0
        public async Task <IActionResult> Post()
        {
            var obj = new UploadHandler(this);

            return(await obj.Run());
        }
Example #20
0
        static internal IEnumerator POST(string url, Dictionary <string, string> headers, Dictionary <string, string> parameters, int timeOut, System.Action <string> completed)
        {
            UploadHandler uploadHandler = null;
            WWWForm       form          = new WWWForm();

            if (headers.ContainsKey("Content-Type"))
            {
                if (headers["Content-Type"] == "application/json")
                {
                    string jsonData = JsonWriter.Serialize(parameters);
                    byte[] bodyRaw  = Encoding.UTF8.GetBytes(jsonData);
                    uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
                }
                else
                {
                    form = new WWWForm();
                    foreach (KeyValuePair <string, string> parameter in parameters)
                    {
                        form.AddField(parameter.Key, parameter.Value);
                    }
                }
            }

            UnityWebRequest www = UnityWebRequest.Post(url, form);

            www.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            www.uploadHandler   = uploadHandler;

            foreach (KeyValuePair <string, string> header in headers)
            {
                string headerKey   = Escape(header.Key);
                string headerValue = Escape(header.Value);
                www.SetRequestHeader(headerKey, headerValue);
            }

#if UNITY_2017_3_OR_NEWER
            if (timeOut > 0)
            {
                www.timeout = timeOut;
            }

            yield return(www.SendWebRequest());

            if (www.isNetworkError)
            {
                completed(www.error);
            }
            else
            {
                completed(www.downloadHandler.text);
            }
#else
            yield return(www.Send());

            if (www.isError)
            {
                completed(www.error);
            }
            else
            {
                completed(www.downloadHandler.text);
            }
#endif
        }
Example #21
0
        public void ProcessRequest(HttpContext context)
        {
            Handler action = null;

            switch (context.Request["action"])
            {
            case "config":
                action = new ConfigHandler(context);
                break;

            case "uploadimage":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("imageAllowFiles"),
                    PathFormat      = Config.GetString("imagePathFormat"),
                    SizeLimit       = Config.GetInt("imageMaxSize"),
                    UploadFieldName = Config.GetString("imageFieldName")
                });
                break;

            case "uploadscrawl":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = new string[] { ".png" },
                    PathFormat      = Config.GetString("scrawlPathFormat"),
                    SizeLimit       = Config.GetInt("scrawlMaxSize"),
                    UploadFieldName = Config.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                });
                break;

            case "uploadvideo":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("videoAllowFiles"),
                    PathFormat      = Config.GetString("videoPathFormat"),
                    SizeLimit       = Config.GetInt("videoMaxSize"),
                    UploadFieldName = Config.GetString("videoFieldName")
                });
                break;

            case "uploadfile":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("fileAllowFiles"),
                    PathFormat      = Config.GetString("filePathFormat"),
                    SizeLimit       = Config.GetInt("fileMaxSize"),
                    UploadFieldName = Config.GetString("fileFieldName")
                });
                break;

            case "listimage":
                action = new ListFileManager(context, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
                break;

            case "listfile":
                action = new ListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
                break;

            case "catchimage":
                action = new CrawlerHandler(context);
                break;

            default:
                action = new NotSupportedHandler(context);
                break;
            }
            action.Process();
        }
Example #22
0
        public ActionResult FileUploader()
        {
            HttpContext context = System.Web.HttpContext.Current;
            Handler     action  = new NotSupportedHandler(context);

            switch (Request["action"])//管理员用
            {
            case "config":
                action = new ConfigHandler(context);
                break;

            case "uploadimage":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
                    PathFormat      = UeditorConfig.GetString("imagePathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("imageMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("imageFieldName")
                });
                break;

            case "uploadscrawl":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = new[] { ".png" },
                    PathFormat      = UeditorConfig.GetString("scrawlPathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("scrawlMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                });
                break;

            case "catchimage":
                action = new CrawlerHandler(context);
                break;

            case "uploadvideo":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
                    PathFormat      = UeditorConfig.GetString("videoPathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("videoMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("videoFieldName")
                });
                break;

            case "uploadfile":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
                    PathFormat      = UeditorConfig.GetString("filePathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("fileMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("fileFieldName")
                });
                break;

            case "listimage":
                action = new ListFileManager(context, UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
                break;

            case "listfile":
                action = new ListFileManager(context, UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
                break;
            }
            #region 用户通用方法
            //switch (Request["action"])//通用
            //{
            //    case "config":
            //        action = new ConfigHandler(context);
            //        break;
            //    case "uploadimage":
            //        action = new UploadHandler(context, new UploadConfig()
            //        {
            //            AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
            //            PathFormat = UeditorConfig.GetString("imagePathFormat"),
            //            SizeLimit = UeditorConfig.GetInt("imageMaxSize"),
            //            UploadFieldName = UeditorConfig.GetString("imageFieldName")
            //        });
            //        break;
            //    case "uploadscrawl":
            //        action = new UploadHandler(context, new UploadConfig()
            //        {
            //            AllowExtensions = new[] { ".png" },
            //            PathFormat = UeditorConfig.GetString("scrawlPathFormat"),
            //            SizeLimit = UeditorConfig.GetInt("scrawlMaxSize"),
            //            UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
            //            Base64 = true,
            //            Base64Filename = "scrawl.png"
            //        });
            //        break;
            //    case "catchimage":
            //        action = new CrawlerHandler(context);
            //        break;
            //}
            #endregion
            #region 管理员权限使用方法
            //UserInfoOutputDto user = HttpContext.Session.GetByRedis<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
            //if (user.IsAdmin)
            //{
            //    switch (Request["action"])//管理员用
            //    {
            //        case "uploadvideo":
            //            action = new UploadHandler(context, new UploadConfig()
            //            {
            //                AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
            //                PathFormat = UeditorConfig.GetString("videoPathFormat"),
            //                SizeLimit = UeditorConfig.GetInt("videoMaxSize"),
            //                UploadFieldName = UeditorConfig.GetString("videoFieldName")
            //            });
            //            break;
            //        case "uploadfile":
            //            action = new UploadHandler(context, new UploadConfig()
            //            {
            //                AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
            //                PathFormat = UeditorConfig.GetString("filePathFormat"),
            //                SizeLimit = UeditorConfig.GetInt("fileMaxSize"),
            //                UploadFieldName = UeditorConfig.GetString("fileFieldName")
            //            });
            //            break;
            //        case "listimage":
            //            action = new ListFileManager(context, UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
            //            break;
            //        case "listfile":
            //            action = new ListFileManager(context, UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
            //            break;
            //    }
            //}
            #endregion
            string result = action.Process();
            return(Content(result, ContentType.Json, Encoding.UTF8));
        }
Example #23
0
        public async Task <ActionResult> UeditorFileUploader()
        {
            UserInfoDto user   = HttpContext.Session.Get <UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
            var         action = Request.Query["action"].ToString() switch //通用
            {
                "config" => (Handler) new ConfigHandler(HttpContext),
                "uploadimage" => new UploadHandler(HttpContext, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
                    PathFormat      = "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\') + UeditorConfig.GetString("imagePathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("imageMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("imageFieldName")
                }),
                "uploadscrawl" => new UploadHandler(HttpContext, new UploadConfig()
                {
                    AllowExtensions = new[]
                    {
                        ".png"
                    },
                    PathFormat      = "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\') + UeditorConfig.GetString("scrawlPathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("scrawlMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                }),
                "catchimage" => new CrawlerHandler(HttpContext),
                _ => new NotSupportedHandler(HttpContext)
            };

            if (user.IsAdmin)
            {
                switch (Request.Query["action"])//管理员用
                {
                //case "uploadvideo":
                //    action = new UploadHandler(context, new UploadConfig()
                //    {
                //        AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
                //        PathFormat =  "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload") + UeditorConfig.GetString("videoPathFormat"),
                //        SizeLimit = UeditorConfig.GetInt("videoMaxSize"),
                //        UploadFieldName = UeditorConfig.GetString("videoFieldName")
                //    });
                //    break;
                case "uploadfile":
                    action = new UploadHandler(HttpContext, new UploadConfig()
                    {
                        AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
                        PathFormat      = "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\') + UeditorConfig.GetString("filePathFormat"),
                        SizeLimit       = UeditorConfig.GetInt("fileMaxSize"),
                        UploadFieldName = UeditorConfig.GetString("fileFieldName")
                    });
                    break;
                    //case "listimage":
                    //    action = new ListFileManager(context, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "/upload") + UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
                    //    break;
                    //case "listfile":
                    //    action = new ListFileManager(context, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "/upload") + UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
                    //    break;
                }
            }

            string result = await action.Process();

            return(Content(result, ContentType.Json));
        }
Example #24
0
 public void ProcessRequest(HttpContext context)
 {
     IUser user = UserContext.CurrentUser;
     if (user == null)
     {
         context.Response.Redirect(SiteUrls.Instance().Login());
     }
     Handler action = null;
     switch (context.Request["action"])
     {
         case "config":
             action = new ConfigHandler(context);
             break;
         case "uploadimage":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = Config.GetStringList("imageAllowFiles"),
                 PathFormat = Config.GetString("imagePathFormat"),
                 SizeLimit = Config.GetInt("imageMaxSize"),
                 UploadFieldName = Config.GetString("imageFieldName")
             });
             break;
         case "uploadscrawl":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = new string[] { ".png" },
                 PathFormat = Config.GetString("scrawlPathFormat"),
                 SizeLimit = Config.GetInt("scrawlMaxSize"),
                 UploadFieldName = Config.GetString("scrawlFieldName"),
                 Base64 = true,
                 Base64Filename = "scrawl.png"
             });
             break;
         case "uploadvideo":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = Config.GetStringList("videoAllowFiles"),
                 PathFormat = Config.GetString("videoPathFormat"),
                 SizeLimit = Config.GetInt("videoMaxSize"),
                 UploadFieldName = Config.GetString("videoFieldName")
             });
             break;
         case "uploadfile":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = Config.GetStringList("fileAllowFiles"),
                 PathFormat = Config.GetString("filePathFormat"),
                 SizeLimit = Config.GetInt("fileMaxSize"),
                 UploadFieldName = Config.GetString("fileFieldName")
             });
             break;
         case "listimage":
             action = new ListFileManager(context, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
             break;
         case "listfile":
             action = new ListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
             break;
         case "catchimage":
             action = new CrawlerHandler(context);
             break;
         default:
             action = new NotSupportedHandler(context);
             break;
     }
     action.Process();
 }
Example #25
0
 public void Requesting_Token_Without_Override_Flag_Should_Be_Denied()
 {
     Token = UploadHandler.RequestUploadToken(TargetFilePath, false, SourceFile.Length, "");
 }
 public void add(string stringContent)
 {
     byte[] byteContentRaw = new UTF8Encoding().GetBytes(stringContent);
     _uploadHandler = (UploadHandler) new UploadHandlerRaw(byteContentRaw);
 }
 public AssetUploader (string assetName, string description, UUID assetID, UUID inventoryItem,
                       UUID parentFolderID, string invType, string assetType, string path,
                       uint everyoneMask, uint groupMask, uint nextOwnerMask, UploadHandler action)
 {
     m_assetName = assetName;
     m_assetDes = description;
     newAssetID = assetID;
     inventoryItemID = inventoryItem;
     uploaderPath = path;
     parentFolder = parentFolderID;
     m_assetType = assetType;
     m_invType = invType;
     m_everyone_mask = everyoneMask;
     m_group_mask = groupMask;
     m_next_owner_mask = nextOwnerMask;
     m_uploadCompleteHandler = action;
 }
Example #28
0
    public Task ExecuteAsync(HttpContext context)
    {
        UploadHandler routeHandler = context.RequestServices.GetRequiredService <UploadHandler>();

        return(routeHandler.ExecuteAsync(context));
    }
        public void ProcessRequest(HttpContext context)
        {
            Handler action = null;

            switch (context.Request["action"])
            {
            case "config":
                action = new ConfigHandler(context);
                break;

            case "uploadimage":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions  = Config.GetStringList("imageAllowFiles"),
                    PathFormat       = Config.GetString("imagePathFormat"),
                    SizeLimit        = Config.GetInt("imageMaxSize"),
                    UploadFieldName  = Config.GetString("imageFieldName"),
                    ImageServicePath = Config.GetString("imageServicePath")
                });
                break;

            case "uploadscrawl":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = new string[] { ".png" },
                    PathFormat      = Config.GetString("scrawlPathFormat"),
                    SizeLimit       = Config.GetInt("scrawlMaxSize"),
                    UploadFieldName = Config.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                });
                break;

            case "uploadvideo":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("videoAllowFiles"),
                    PathFormat      = Config.GetString("videoPathFormat"),
                    SizeLimit       = Config.GetInt("videoMaxSize"),
                    UploadFieldName = Config.GetString("videoFieldName")
                });
                break;

            case "uploadfile":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("fileAllowFiles"),
                    PathFormat      = Config.GetString("filePathFormat"),
                    SizeLimit       = Config.GetInt("fileMaxSize"),
                    UploadFieldName = Config.GetString("fileFieldName")
                });
                break;

            case "listimage":
                action = new ListFileManager(context, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
                break;

            case "listfile":
                action = new ListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
                break;

            case "catchimage":
                action = new CrawlerHandler(context, Config.GetString("imageServicePath"));
                break;

            default:
                action = new NotSupportedHandler(context);
                break;
            }
            action.Response.AddHeader("Access-Control-Allow-Origin", "*");
            action.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            action.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
            action.Process();
        }
Example #30
0
 public void Requesting_Token_With_Overwrite_Flag_Should_Be_Granted()
 {
     Token = UploadHandler.RequestUploadToken(TargetFilePath, true, SourceFile.Length, "");
 }
Example #31
0
        /// <summary>
        /// 文件处理模块
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("Pragma", "no-cache");
            context.Response.AddHeader("Cache-Control", "private, no-cache");
            context.Response.Charset         = "utf-8";
            context.Response.ContentEncoding = Encoding.GetEncoding("utf-8");
            Handler action = null;

            var fun = context.GetStringFromParameters("fun");

            switch (fun)
            {
            case "001":
                action = new UploadHandler(context, new UploadConfig
                {
                    AllowExtensions = Config.GetStringList("imageAllowFiles"),
                    PathFormat      = Config.GetString("imagePathFormat"),
                    SizeLimit       = Config.GetInt("imageMaxSize"),
                    UploadFieldName = Config.GetString("imageFieldName"),
                    PreUrl          = Config.GetString("imageUrlPrefix"),
                    Others          = context.GetStringFromParameters("others")
                });
                break;

            //获取文件记录
            case "002":
                action = new GetFileHandler(context);
                break;

            //接收文件
            case "003":
                action = new UploadPartHandler(context, new UploadConfig
                {
                    AllowExtensions = Config.GetStringList("imageAllowFiles"),
                    PathFormat      = Config.GetString("imagePathFormat"),
                    SizeLimit       = Config.GetInt("imageMaxSize"),
                    UploadFieldName = Config.GetString("imageFieldName"),
                    PreUrl          = Config.GetString("imageUrlPrefix")
                });
                break;

            //通知文件传输结束
            case "004":
                action = new FinishuploadHandler(context, new UploadConfig
                {
                    AllowExtensions = Config.GetStringList("imageAllowFiles"),
                    PathFormat      = Config.GetString("imagePathFormat"),
                    SizeLimit       = Config.GetInt("imageMaxSize"),
                    UploadFieldName = Config.GetString("imageFieldName"),
                    PreUrl          = Config.GetString("imageUrlPrefix")
                });
                break;

            //测试通信
            default:
                var result = new UploadResult {
                    State = UploadState.Success, Url = "测试通信"
                };
                var returnValue = JsonConvert.SerializeObject(result);
                context.Response.Write(returnValue);
                context.Response.End();
                break;
            }
            action?.Process();
        }
    public static IEnumerator SendRequest(string url, MethodsHTTP type, System.Action <bool, string> outputMessage, string arguments = "", string json = "", string token = "", UploadHandler handler = null, List <Headers> headers = null, int timeout = -1, DownloadHandler downloadHandler = null)
    {
        Debug.Log(url + arguments);

        var www = new UnityWebRequest(url + arguments, type.ToString());

        if (timeout < 1)
        {
            www.timeout = 2;
        }
        else
        {
            www.timeout = timeout;
        }

        if (handler != null)
        {
            www.uploadHandler = handler;
        }
        else if (!string.IsNullOrEmpty(json))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
            www.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            www.SetRequestHeader("Content-Type", "application/json");
        }

        if (!string.IsNullOrEmpty(token))
        {
            www.SetRequestHeader("authorization", token);
        }

        if (headers != null && headers.Count > 0)
        {
            headers.ForEach((x) => www.SetRequestHeader(x.name, x.value));
        }

        if (downloadHandler == null)
        {
            www.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        }
        else
        {
            www.downloadHandler = downloadHandler;
        }

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            outputMessage(false, Encoding.UTF8.GetString(www.downloadHandler.data));
            Debug.Log(Encoding.UTF8.GetString(www.downloadHandler.data));
        }
        else
        {
            Debug.Log(Encoding.UTF8.GetString(www.downloadHandler.data));
            outputMessage(true, (Encoding.UTF8.GetString(www.downloadHandler.data)));
        }
    }
Example #33
0
 public APIRequest(string url, string method, DownloadHandler downloadHandler, UploadHandler uploadHandler) : base(url, method, downloadHandler, uploadHandler)
 {
 }