/// <summary> /// File handler demo for classic Asp.Net or HTML. /// To access it in an Javascript ajax request use: <code>var url = "/Handler/FileHandler.ashx";</code>. /// </summary> /// <remarks> /// NOTE. Edit the web.config file to allow the DELETE method in the system.webServer.handlers section /// </remarks> public override async Task ProcessRequestAsync(HttpContext context) { try { // Wrap the request into a HttpRequestBase type HttpRequestBase request = new HttpRequestWrapper(context.Request); // Create and initialize the handler IFileHandler handler = Backload.FileHandler.Create(); handler.Init(request); // Call the execution pipeline and get the result IBackloadResult result = await handler.Execute(); // Write result to the response and flush ResultCreator.Write(context.Response, result); context.Response.Flush(); } catch { context.Response.StatusCode = 500; } }
public async Task <ActionResult> Upload() { try { IFileHandler handler = Backload.FileHandler.Create(); using (var provider = new BackloadDataProvider(this.Request)) { var name = provider.Files[0].FileName; provider.Files[0].FileName = string.Format("{0}.{1}", Guid.NewGuid(), "xlsx"); handler.Init(provider); IBackloadResult result = await handler.Execute(); result.ContentType = "Content-Type: application/json; charset=utf-8"; return(ResultCreator.Create(result)); } } catch (Exception ex) { MvcApplication.log.Error(ex, "Не удалось загрузить файл контактов"); } return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); }
public async Task <ActionResult> FileHandler() { try { // Create and initialize the handler IFileHandler handler = Backload.FileHandler.Create(); // Attach event handlers to events handler.Events.IncomingRequestStarted += Events_IncomingRequestStarted; handler.Events.GetFilesRequestStarted += Events_GetFilesRequestStarted; handler.Events.GetFilesRequestFinished += Events_GetFilesRequestFinished; // Init Backloads execution environment and execute the request handler.Init(HttpContext.Request); IBackloadResult result = await handler.Execute(); // Helper to create an ActionResult object from the IBackloadResult instance return(ResultCreator.Create(result)); } catch { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } }
/// <summary> /// Writes the result directly into the response stream, e.g. for a classic ASP.NET response /// </summary> /// <param name="response">A standard HttpResponse object</param> /// <param name="result">An IBackloadResult object</param> public static void Write(HttpResponse response, IBackloadResult result) { response.StatusCode = (int)result.HttpStatusCode; if ((int)result.HttpStatusCode < 300) { // Write result to the response (Json or file data, default: Json response) if (result.RequestType == RequestType.Default) { // Json response (We use the systems JavaScriptSerializer, you can also use Newtonsoft.Json) IFileStatusResult status = (IFileStatusResult)result; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); if ((status.ClientStatus != null) && (result.Exception == null)) { response.Write(serializer.Serialize(status.ClientStatus)); } } else { // file data (byte array) response IFileDataResult data = (IFileDataResult)result; if ((data.FileData != null) && (result.Exception == null)) { response.BinaryWrite(data.FileData); } } } }
/// <summary> /// Writes the result directly into the response stream, e.g. for a classic ASP.NET response /// </summary> /// <param name="response">A standard HttpResponse object</param> /// <param name="result">An IBackloadResult object</param> public static void Write(HttpResponse response, IBackloadResult result) { response.StatusCode = (int)result.HttpStatusCode; if ((int)result.HttpStatusCode < 300) { // Write result to the response (Json or file data, default: Json response) if (result.RequestType == RequestType.Default) { // Json response (We use the systems JavaScriptSerializer, you can also use Newtonsoft.Json) IFileStatusResult status = (IFileStatusResult)result; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); if ((status.ClientStatus != null) && (result.Exception == null)) response.Write(serializer.Serialize(status.ClientStatus)); } else if ((result.RequestType == RequestType.File) || (result.RequestType == RequestType.Thumbnail)) { // file data (byte array) response IFileDataResult data = (IFileDataResult)result; if ((data.FileData != null) && (result.Exception == null)) response.BinaryWrite(data.FileData); } } }
public async Task <HttpResponseMessage> Get(HttpRequestMessage request, [FromUri(Name = "objectContext")] string userId) { try { // Call the execution pipeline and get the result IBackloadResult result = await _handler.Execute(); // Get the client plugin specific result var clientResult = ((IFileStatusResult)result).ClientStatus; // return result object and status code return(request.CreateResponse(result.HttpStatusCode, clientResult)); #region Optional: Use Backload Api (Services namespace. Pro/Enterprise only) //// Simple demo: Call the GET execution method and get the result //IFileStatus status = await _handler.Services.GET.Execute(); //// Create plugin specific result //result = _handler.Services.Core.CreatePluginResult(); //// return plugin specific result object //return request.CreateResponse(HttpStatusCode.OK, result.ClientStatus); #endregion Optional: Use backload Api (Services namespace. Pro/Enterprise only) } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
/// <summary> /// Returns an ActionResult depending on the requested type (Json or file data) /// </summary> /// <param name="result">An IBackloadResult instance</param> /// <returns>An ActionResult instance</returns> public static ActionResult Create(IBackloadResult result) { if ((int)result.HttpStatusCode < 300) { // RequestType.Default: Json output has been requested (default). // Otherwise a file or a thumbnail (bytes) will be returned. if (result.RequestType == RequestType.Default) return Create((IFileStatusResult)result); else if ((result.RequestType == RequestType.File) || (result.RequestType == RequestType.Thumbnail)) return Create((IFileDataResult)result); } // Http status code >= 300 return new HttpStatusCodeResult(result.HttpStatusCode); }
public async Task <ActionResult> FileHandler() { try { IFileHandler handler = Backload.FileHandler.Create(); handler.Init(HttpContext.Request); IBackloadResult result = await handler.Execute(false); return(ResultCreator.Create(result)); } catch { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } }
public async Task <ActionResult> Upload() { try { IFileHandler handler = Backload.FileHandler.Create(); handler.Events.IncomingRequestStarted += Events_IncomingRequestStarted; handler.Init(this.HttpContext, _hosting); IBackloadResult result = await handler.Execute(); return(ResultCreator.Create(result)); } catch { return(new StatusCodeResult((int)HttpStatusCode.InternalServerError)); } }
public async Task <HttpResponseMessage> Delete(HttpRequestMessage request, string fileName, [FromUri(Name = "objectContext")] string userId) { try { // Call the execution pipeline and get the result IBackloadResult result = await _handler.Execute(); // Get the client plugin specific result var clientResult = ((IFileStatusResult)result).ClientStatus; // return result object and status code return(request.CreateResponse(result.HttpStatusCode, clientResult)); } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
/// <summary> /// Returns an ActionResult depending on the requested type (Json or file data) /// </summary> /// <param name="result">An IBackloadResult instance</param> /// <returns>An ActionResult instance</returns> public static ActionResult Create(IBackloadResult result) { if ((int)result.HttpStatusCode < 300) { // RequestType.Default: Json output has been requested (default). // Otherwise a file or a thumbnail (bytes) will be returned. if (result.RequestType == RequestType.Default) { return(Create((IJsonResult)result)); } else if ((result.RequestType == RequestType.File) || (result.RequestType == RequestType.Thumbnail)) { return(Create((IFileDataResult)result)); } } // Http status code >= 300 return(new StatusCodeResult((int)result.HttpStatusCode)); }
public async Task <ActionResult> FileHandler() { IBackloadResult result = null; IFileStatus status = null; try { // Create and initialize the handler IFileHandler handler = Backload.FileHandler.Create(); handler.Init(HttpContext.Request); // This demo calls high level API methods. // Http methhod related API methods are in handler.Services.[HttpMethod]. // Low level API methods are in handler.Services.Core if (handler.Context.HttpMethod == "GET") { status = await handler.Services.GET.Execute(); } else if (handler.Context.HttpMethod == "POST") { status = await handler.Services.POST.Execute(); } else if (handler.Context.HttpMethod == "DELETE") { status = await handler.Services.DELETE.Execute(); } // Create a client plugin specific result. // In this example we could simply call CreateResult(), because handler.FilesStatus also has the IFileStatus object result = handler.Services.Core.CreatePluginResult(status, Backload.Contracts.Context.Config.PluginType.JQueryFileUpload); // Helper to create an ActionResult object from the IBackloadResult instance return(ResultCreator.Create(result)); } catch { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } }
// Executes DELETE requsts private async Task <ActionResult> DeleteHandler(IFileHandler handler) { // Get the file to delete handler.FileStatus = handler.Services.DELETE.GetRequestStatus(); IFileStatusItem file = handler.FileStatus.Files[0]; using (FilesModel db = new FilesModel()) { Guid id = Guid.Parse(file.FileName); File f = db.Files.Find(id); db.Files.Remove(f); await db.SaveChangesAsync(); } // Create client plugin specific result and return an ActionResult IBackloadResult result = handler.Services.Core.CreatePluginResult(); return(ResultCreator.Create((IFileStatusResult)result)); }
public ActionResult FileHandler() { try { // Create and initialize the handler IFileHandler handler = Backload.FileHandler.Create(); handler.Init(HttpContext.Request); // Call the execution pipeline and get the result IBackloadResult result = handler.Execute(); // Helper to create an ActionResult object from the IBackloadResult instance return(ResultCreator.Create(result)); } catch { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } }
public async Task <HttpResponseMessage> Get(HttpRequestMessage request, string fileName, [FromUri(Name = "objectContext")] string userId) { try { // Call the execution pipeline and get the result IBackloadResult result = await _handler.Execute(); // Get the client plugin specific result var clientResult = (IFileDataResult)result; //// Create response ojbect (bytes) HttpResponseMessage response = request.CreateResponse(result.HttpStatusCode); response.Content = new ByteArrayContent(clientResult.FileData); response.Content.Headers.ContentType = new MediaTypeHeaderValue(result.ContentType); return(response); } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
public async Task <ActionResult> FileHandler() { try { // Create and initialize the handler IFileHandler handler = Backload.FileHandler.Create(); handler.Init(HttpContext.Request); // Call the execution pipeline and get the result IBackloadResult result = await handler.Execute(); return(RedirectToAction("Index", "Home")); // Helper to create an ActionResult object from the IBackloadResult instance //return ResultCreator.Create(result); } catch { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } }
// Executes GET requsts for all files private static ActionResult GetHandler(IFileHandler handler) { IFileStatus status = new FileStatus(); using (FilesModel db = new FilesModel()) { foreach (var row in db.Files) { string url = handler.Context.Request.Url.OriginalString + "?fileName=" + row.Id.ToString(); IFileStatusItem file = new FileStatusItem() { ContentType = row.Type, DeleteType = "DELETE", FileName = row.Name, FileSize = row.Size, OriginalName = row.Original, Progress = "100", Success = true, ThumbnailUrl = row.Preview, // Set an identifier for GET and DELETE requests DeleteUrl = url, FileUrl = url }; status.Files.Add(file); } } handler.FileStatus = status; // Create client plugin specific result and return an ActionResult IBackloadResult result = handler.Services.Core.CreatePluginResult(); return(ResultCreator.Create((IFileStatusResult)result)); }
// Executes POST requsts private async Task <ActionResult> PostHandler(IFileHandler handler) { // Get the posted file with meta data from the request handler.FileStatus = await handler.Services.POST.GetPostedFiles(); if (handler.FileStatus != null) { Guid id = Guid.NewGuid(); IFileStatusItem file = handler.FileStatus.Files[0]; // Read the file data (bytes) byte[] data = null; using (System.IO.MemoryStream stream = new System.IO.MemoryStream((int)file.FileSize)) { await file.FileStream.CopyToAsync(stream); data = stream.ToArray(); } // Create the thumbnail await handler.Services.POST.CreateThumbnail(file); // Create a base64 encoded data url for the thumbnail we can return in Json await handler.Services.Core.CreateThumbnailDataUrls(); // This will change the url query parameter fileName to the id of the // new table row, so we can identify the file in a DELETE and GET request file.FileUrl = file.DeleteUrl.Replace(file.FileName, id.ToString()); file.DeleteUrl = file.FileUrl; // Store to db using (FilesModel db = new FilesModel()) { // File entity represents a table row File row = new File() { Id = id, Data = data, Name = file.FileName, Original = file.OriginalName, Size = file.FileSize, Type = file.ContentType, UploadTime = DateTime.Now, Preview = file.ThumbnailUrl }; File f = db.Files.Add(row); await db.SaveChangesAsync(); }; } // Create client plugin specific result and return an ActionResult IBackloadResult result = handler.Services.Core.CreatePluginResult(); return(ResultCreator.Create((IFileStatusResult)result)); }