Skip to content

Instantly share code, notes, and snippets.

@smiler
Created November 7, 2012 15:41
Show Gist options
  • Save smiler/4032328 to your computer and use it in GitHub Desktop.
Save smiler/4032328 to your computer and use it in GitHub Desktop.
// http://stackoverflow.com/questions/4350686/using-plupload-with-asp-net-c
<%@ WebHandler Language="C#" Class="Upload" %>
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Web;
public class Upload : IHttpHandler {
public void ProcessRequest(HttpContext context) {
/**
* If 'newTicket' is "false", then the directory to upload to already exists and we can extract it from
* the 'ticketID' POST parameter.
*
* If 'newTicket' is "true", then this is a new Ticket submission so we need to work with a NEW directory
* on the server, so the ID needs to be 1 more than the total number of directories in ~/TicketUploads/
*/
String newTicket = context.Request["newTicket"] != null ? context.Request["newTicket"] : String.Empty;
int theID = -1;
if (newTicket.Equals("true")) {
// we need to calculate a new ID
theID = getNewID(context); // calculate the new ID = # of rows
theID++; // add 1 to make it unique
} else if (newTicket.Equals("false")) {
// we can just get the ID from the POST parameter
theID = context.Request["ticketID"] != null ? Convert.ToInt32(context.Request["ticketID"]) : -1;
} else {
// something went wrong with the 'newTicket' POST parameter
context.Response.ContentType = "text/plain";
context.Response.Write("Error with 'newTicket' POST parameter.");
}
// if theID is negative, something went wrong... can't continue
if (theID < 0) {
return;
}
// ready to read the files being uploaded and upload them to the correct directory
int chunk = context.Request["chunk"] != null ? int.Parse(context.Request["chunk"]) : 0;
string fileName = context.Request["name"] != null ? context.Request["name"] : string.Empty;
var uploadPath = context.Server.MapPath("~/TicketUploads/" + theID + "/");
HttpPostedFile fileUpload = context.Request.Files[0];
// if the NEW directory doesn't exist, create it
DirectoryInfo di = new DirectoryInfo("" + uploadPath + "");
if (!(di.Exists)) {
di.Create();
}
using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append)) {
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
context.Response.ContentType = "text/plain";
context.Response.Write("File uploaded.");
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment