public GeneralResult <string[]> upload2(Stream stream) { GeneralResult <string[]> result = new GeneralResult <string[]>(); try { List <string> paths = new List <string>(); MultipartParser parser = new MultipartParser(stream); string error; string file_name = Guid.NewGuid() + "." + parser.Filename.Split('.')[1]; string single = FileOperation.SaveFile(out error, file_name, parser.FileContents); single = single.Substring(AppHome.BaseDirectory.Length - 1); single = single.Replace("\\", "/"); if (error == "") { paths.Add(single); } result.success = true; result.data = paths.ToArray(); } catch (Exception ex) { SystemLog.WriteErrorLog("请求失败", "2002", ex.Message, ex.StackTrace); } return(result); }
public string ImportKML(Stream stream) { MultipartParser parser = new MultipartParser(stream); XmlDocument doc = new XmlDocument(); var filename = parser.Filename; string fileContent = System.Text.Encoding.UTF8.GetString(parser.FileContents); return(fileContent); }
public HttpResponseMessage Post() { MultipartParser parser = new MultipartParser(HttpContext.Current.Request.InputStream); if (!parser.Success) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } PredictAndSaveRequest(parser); return(Request.CreateResponse(HttpStatusCode.Accepted)); }
//Require Namespace: using System.IO public bool UpdateUserDetail(Stream stream) { try { //Create an Object of byte[] byte[] buf = new byte[10000000]; //Initialise an Object of MultipartParser Class With Requested Stream MultipartParser parser = new MultipartParser(stream); //Check that we have not null value in requested stream if (parser != null && parser.Success) { //Fetch Requested Formdata (content) //(for this example our requested formdata are UserName[String]) foreach (var item in parser.MyContents) { //Check our requested fordata if (item.PropertyName == "UserName") { string RequestedName = item.StringData; } } //Create a GUID for Image Name string ImageName = Guid.NewGuid().ToString(); //Image Path string SaveImagePath = "D:/DemoProject/DemoMultipartWCF/DemoMultipartWCF/MyFile/"; //Ensure That WE have the right path and Directory if (!Directory.Exists(SaveImagePath)) { //If Directory Not Exists Then Create a Directory Directory.CreateDirectory(SaveImagePath); } //Fetch File Content & Save that Image HERE (for this example our requested FileContent is ProfilePicture[File]) string ImagePathWithImageName = SaveImagePath + ImageName + ".bmp"; SaveImageFile(parser.FileContents, ImagePathWithImageName); return(true); } return(false); } catch { //Do Code For Log or Handle Exception return(false); } }
/// <summary> /// Save uploaded file to SP document library /// </summary> /// <param name="fileName"></param> /// <param name="fileStream"></param> /// <returns></returns> public Message SaveFile(string teamId, Stream fileStream) { string response = string.Empty; int teamID = Int16.Parse(teamId); string fileGuid = Guid.NewGuid().ToString() + ".docx"; Dictionary <string, string> responseData = new Dictionary <string, string>(); var serializer = new DataContractJsonSerializer(typeof(Dictionary <string, string>), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); try { KPTimer timer = EventLogger.Timer; MultipartParser parser = new MultipartParser(fileStream); if (parser.Success) { // save the file SPDataAccess spDataAccess = new SPDataAccess(); spDataAccess.SaveFileToLibrary(teamID, fileGuid, parser.FileContents); // generate response responseData.Add("FileName", fileGuid); responseData.Add("Elapsed", timer.ElapsedMilliseconds().ToString()); responseData.Add("Bytes", parser.FileContents.Length.ToString()); } else { string errMsg = string.Empty; ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; responseData.Add("Error", "Error parsing filestream"); if (parser.FileContents == null) { responseData.Add("FileContents", "no file content sent in request."); } if (parser.ContentType == null) { responseData.Add("ContentType", "no file content-type found in request."); } } } catch (Exception ex) { ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; responseData.Add("Exception", ex.Message); if (ex.InnerException != null) { responseData.Add("InnerException", ex.InnerException.Message); } } return(this.ctx.CreateJsonResponse <Dictionary <string, string> >(responseData, serializer)); }
public ImageProcessor(MultipartParser parser) { _parser = parser; // Switch data format: switch (Resources.ImageFormat.ToLower()) { case ".jpeg": case ".jpg": using (MemoryStream original = new MemoryStream(parser.FileContents)) using (MemoryStream output = new MemoryStream()) using (Image jpg = Image.FromStream(original)) { jpg.Save(output, ImageFormat.Jpeg); Data = output.ToArray(); } return; case ".png": using (MemoryStream original = new MemoryStream(parser.FileContents)) using (MemoryStream output = new MemoryStream()) using (Image png = Image.FromStream(original)) { png.Save(output, ImageFormat.Png); Data = output.ToArray(); } return; case ".bmp": using (MemoryStream original = new MemoryStream(parser.FileContents)) using (MemoryStream output = new MemoryStream()) using (Image bmp = Image.FromStream(original)) { bmp.Save(output, ImageFormat.Bmp); Data = output.ToArray(); } return; case ".gif": using (MemoryStream original = new MemoryStream(parser.FileContents)) using (MemoryStream output = new MemoryStream()) using (Image gif = Image.FromStream(original)) { gif.Save(output, ImageFormat.Gif); Data = output.ToArray(); } return; default: throw new InvalidDataException("Unknown type " + Resources.ImageFormat); } }
private void Parse(Stream stream) { this.Success = false; if (!stream.CanRead) { return; } // Read the stream into a byte array byte[] data = MultipartParser.ToByteArray(stream); if (data.Length < 1) { return; } // finding the delimiter (the string in the beginning and end of the file int delimeterIndex = MultipartParser.SimpleBoyerMooreSearch(data, Encoding.UTF8.GetBytes("\r\n")); // here we got delimeter index if (delimeterIndex == -1) { return; } byte[] delimeterBytes = new byte[delimeterIndex]; Array.Copy(data, delimeterBytes, delimeterIndex); // removing the very first couple of lines, till we get the beginning of the JPG file byte[] newLineBytes = Encoding.UTF8.GetBytes("\r\n\r\n"); int startIndex = 0; startIndex = MultipartParser.SimpleBoyerMooreSearch(data, newLineBytes); if (startIndex == -1) { return; } int startIndexWith2Lines = startIndex + 4; // 4 is the bytes of "\r\n\r\n" int newLength = data.Length - startIndexWith2Lines; byte[] newByteArray = new byte[newLength]; Array.Copy(data, startIndex + 4, newByteArray, 0, newLength - 1); // check for the end of the stream, is ther same delimeter int isThereDelimeterInTheEnd = MultipartParser.SimpleBoyerMooreSearch(newByteArray, delimeterBytes); if (isThereDelimeterInTheEnd == -1) { return; // the file corrupted so } int endIndex = isThereDelimeterInTheEnd - delimeterBytes.Length; byte[] lastArray = new byte[endIndex]; Array.Copy(newByteArray, 0, lastArray, 0, endIndex); this.FileContents = lastArray; this.Success = true; }
public void UploadChunk(Stream data) { var mode = HttpContext.Current.Request.ReadEntityBodyMode; MultipartParser parser = new MultipartParser(data); if (parser.Success) { // Save the file string filename = parser.Filename; string contentType = parser.ContentType; byte[] filecontent = parser.FileContents; string physicalFilePath = Path.Combine(Configurations.UploadsFolder, filename); File.WriteAllBytes(physicalFilePath, filecontent); } }
public string ImportImage(Stream stream) { string tempPath = "/Upload"; string path = HttpContext.Current.Server.MapPath(tempPath); string filename = Guid.NewGuid() + ".png"; string localPng = path + "\\" + filename; MultipartParser parser = new MultipartParser(stream); using (var ms = new MemoryStream(parser.FileContents)) { Image img = Image.FromStream(ms); img.Save(localPng, ImageFormat.Png); } return(tempPath + "/" + filename); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void processMultiPart(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws java.io.IOException private void processMultiPart(HttpServletRequest req, HttpServletResponse resp) { PrintWriter @out = resp.Writer; resp.ContentType = "text/plain"; MultipartParser mp = new MultipartParser(req, 2048); Part part = null; while ((part = mp.readNextPart()) != null) { string name = part.Name.Trim(); if (part.Param) { // it's a parameter part ParamPart paramPart = (ParamPart)part; string value = paramPart.StringValue.Trim(); LOG.info("param; name=" + name + ", value=" + value); @out.print("param; name=" + name + ", value=" + value); } else if (part.File) { // it's a file part FilePart filePart = (FilePart)part; string fileName = filePart.FileName; if (!string.ReferenceEquals(fileName, null)) { // the part actually contained a file // StringWriter sw = new StringWriter(); // long size = filePart.writeTo(new File(System // .getProperty("java.io.tmpdir"))); System.IO.MemoryStream baos = new System.IO.MemoryStream(); long size = filePart.writeTo(baos); LOG.info("file; name=" + name + "; filename=" + fileName + ", filePath=" + filePart.FilePath + ", content type=" + filePart.ContentType + ", size=" + size); @out.print(string.Format("{0}: {1}", name, (StringHelperClass.NewString(baos.toByteArray())).Trim())); } else { // the field did not contain a file LOG.info("file; name=" + name + "; EMPTY"); } @out.flush(); } } resp.Status = HttpServletResponse.SC_OK; }
private void HandleUpload(HttpListenerContext context) { var request = context.Request; if (request.Url.AbsolutePath.Contains("upload")) { var fileKey = request.Headers["File-Key"]; var parser = new MultipartParser(context.Request.InputStream); using (var writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8)) { if (parser.Success) { var saved = SaveFile(fileKey, parser.FileContents); var responseObject = new { fileKey, success = saved, message = "File Uploaded!" }; var json = JsonConvert.SerializeObject(responseObject); writer.WriteLine(json); } else { var responseObject = new { fileKey, success = false, message = "The posted file was not recognised." }; var json = JsonConvert.SerializeObject(responseObject); writer.WriteLine(json); } context.Response.AddHeader("Access-Control-Allow-Origin", "*"); context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; context.Response.Close(); context.Response.OutputStream.Close(); } } }
private void PredictAndSaveRequest(MultipartParser parser) { using (var db = new DogsVsCatsEntities()) { Predictor predictor = new Predictor(); var predictionResult = predictor.PredictImage(parser.FileContents); var prediction = new Prediction { Id = Guid.NewGuid(), ContentType = parser.ContentType, FileName = parser.Filename, CreatedOn = DateTimeOffset.UtcNow, Data = parser.FileContents, DogProbability = predictionResult.dogProbability, CatProbability = predictionResult.catProbability }; db.Predictions.Add(prediction); db.SaveChanges(); } }
public void SaveImage(MultipartParser parser) { ImageProcessor processor = new ImageProcessor(parser); File.WriteAllBytes(Resources.BasePath + "/resources/images/users/User" + this.id + Resources.ImageFormat, processor.Data); }
public Arena.Services.Contracts.ModifyResult UpdateSmallGroupPhoto(System.IO.Stream stream, int id) { try { Arena.SmallGroup.Group group = new Arena.SmallGroup.Group(id); Boolean accessDenied = false; // If this person isn't the outright leader and they don't have edit access if (group.Leader.PersonID != ArenaContext.Current.Person.PersonID && RestApi.GroupClusterOperationAllowed(ArenaContext.Current.Person.PersonID, group.GroupClusterID, OperationType.Edit) == false) { accessDenied = true; // Do a deeper dive into each member of the group foreach (GroupMember gm in group.Members) { if (gm.Active && gm.Role.Value == "Leader") { accessDenied = false; break; } } } if (accessDenied) { throw new Exception("Access denied."); } MultipartParser parser = new MultipartParser(stream); if (parser.Success) { // Make sure this is a real image MemoryStream ms = new MemoryStream(parser.FileContents); String myStream = Encoding.ASCII.GetString(ms.ToArray()); Image image = Image.FromStream(ms); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo codec = codecs.First(c => c.FormatID == image.RawFormat.Guid); // If we have an existing image, delete it if (group.ImageBlob.BlobID > 0) { group.ImageBlob.Delete(); } // Create a new file Utility.ArenaImage arenaImage = new Utility.ArenaImage(); // Update everything arenaImage.ByteArray = parser.FileContents; arenaImage.MimeType = codec.MimeType; arenaImage.OriginalFileName = Path.GetFileNameWithoutExtension(parser.Filename) + "." + codec.FormatDescription.ToLower().Replace("jpeg", "jpg"); arenaImage.FileExtension = codec.FormatDescription.ToLower().Replace("jpeg", "jpg"); // Save the file group.ImageBlob = arenaImage; group.ImageBlob.Save(ArenaContext.Current.User.Identity.Name); group.Save(ArenaContext.Current.User.Identity.Name); } return(new Services.Contracts.ModifyResult() { Link = Contracts.SmallGroupMapper.getImageThumbnailUrl(group.ImageBlob), Successful = true.ToString() }); } catch (Exception ex) { return(new Services.Contracts.ModifyResult() { Successful = false.ToString(), ErrorMessage = string.Format("{0} - {1}", ex.GetType().ToString(), ex.Message) }); } }
/// <summary> /// 分发器 /// </summary> /// <param name="stream"></param> /// <returns></returns> public Message Action(string method, Stream stream) { try { int operation_user; string token; Dictionary <string, string> param = Utilities.GetQueryParam(stream); operation_user = param.ContainsKey("operation_user") ? Convert.ToInt32(param["operation_user"]) : 0; token = param.ContainsKey("token") ? param["token"] : ""; string str_result = ""; if (!Token.ValidToken(operation_user, token)) { GeneralResult <string> result = new GeneralResult <string>("token过期,请重新登录"); str_result = JsonConvert.SerializeObject(result); } else { switch (method) { case "get_app_version": { string error = ""; string type = param.ContainsKey("type") ? param["type"] : ""; string version = GetFileVersion(type); GeneralResult <string> result = new GeneralResult <string>(); result.data = version; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_homepage_picture": { string error = ""; string type = param.ContainsKey("type") ? param["type"] : ""; string[] paths = QueryHomepagePicture(out error, type); GeneralResult <string[]> result = new GeneralResult <string[]>(); result.data = paths; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_index_other_content": { int id = param.ContainsKey("userid") ? Convert.ToInt32(param["userid"]) : 0; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; GeneralResult <Dictionary <string, string> > result = new GeneralResult <Dictionary <string, string> >(); string str_error = ""; Dictionary <string, string> data = QueryIndexContent(out str_error, id, dep); if (str_error == "") { result.success = true; result.data = data; } else { result.message = str_error; } str_result = JsonConvert.SerializeObject(result); break; } case "count_sign_by_dep": { string dep = param.ContainsKey("dep") ? param["dep"] : ""; string startTime = param.ContainsKey("start_time") ? param["start_time"] : ""; string endTime = param.ContainsKey("end_time") ? param["end_time"] : ""; GeneralResult <string> result = new GeneralResult <string>(); string str_error = ""; string data = CountSignByDep(out str_error, dep, startTime, endTime); if (str_error == "") { result.success = true; result.data = data; } else { result.message = str_error; } str_result = JsonConvert.SerializeObject(result); break; } case "count_urinalysis_by_dep": { string dep = param.ContainsKey("dep") ? param["dep"] : ""; string startTime = param.ContainsKey("start_time") ? param["start_time"] : ""; string endTime = param.ContainsKey("end_time") ? param["end_time"] : ""; GeneralResult <string> result = new GeneralResult <string>(); string str_error = ""; string data = CountUrinalysisByDep(out str_error, dep, startTime, endTime); if (str_error == "") { result.success = true; result.data = data; } else { result.message = str_error; } str_result = JsonConvert.SerializeObject(result); break; } case "upload_news_images": { string images = param.ContainsKey("images") ? param["images"] : ""; MultipartParser parser = new MultipartParser(param["images"]); string[] paths = parser.GetBase64Images(); GeneralResult <string[]> result = new GeneralResult <string[]>(); if (paths.Length > 0) { result.success = true; result.data = paths; } str_result = JsonConvert.SerializeObject(result); break; } case "add_news": { int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string title = param.ContainsKey("title") ? param["title"] : ""; string content = param.ContainsKey("content") ? param["content"] : ""; string type = param.ContainsKey("type") ? param["type"] : ""; string photo = param.ContainsKey("photo") ? param["photo"] : ""; int order = param.ContainsKey("order") ? Convert.ToInt32(param["order"]) : 0; int top = param.ContainsKey("top") ? Convert.ToInt32(param["top"]) : 0; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; string error = ""; bool flag = AddNews(out error, title, content, user, type, photo, order, top, dep); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_news": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string title = param.ContainsKey("title") ? param["title"] : ""; string content = param.ContainsKey("content") ? param["content"] : ""; string type = param.ContainsKey("type") ? param["type"] : ""; string photo = param.ContainsKey("photo") ? param["photo"] : ""; int order = param.ContainsKey("order") ? Convert.ToInt32(param["order"]) : 0; int top = param.ContainsKey("top") ? Convert.ToInt32(param["top"]) : 0; string error = ""; bool flag = UpdateNews(out error, id, title, content, user, type, photo, order, top); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "delete_news": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteNews(out error, id); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_news": { int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string title = param.ContainsKey("title") ? param["title"] : ""; string type = param.ContainsKey("type") ? param["type"] : ""; int top = param.ContainsKey("top") ? Convert.ToInt32(param["top"]) : 0; string error = ""; News[] news = QueryNews(out error, type, user, title, top); GeneralResult <News[]> result = new GeneralResult <News[]>(); result.data = news; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "add_sign": { int user1 = param.ContainsKey("user1") ? Convert.ToInt32(param["user1"]) : 0; string location1 = param.ContainsKey("location1") ? param["location1"] : ""; string address1 = param.ContainsKey("address1") ? param["address1"] : ""; string time1 = param.ContainsKey("time1") ? param["time1"] : ""; string photo = param.ContainsKey("photo") ? param["photo"] : ""; string type = param.ContainsKey("type") ? param["type"] : ""; string state = param.ContainsKey("state") ? param["state"] : ""; string remark = param.ContainsKey("remark") ? param["remark"] : ""; int user2 = param.ContainsKey("user2") ? Convert.ToInt32(param["user2"]) : 0; string location2 = param.ContainsKey("location2") ? param["location2"] : ""; string address2 = param.ContainsKey("address2") ? param["address2"] : ""; string time2 = param.ContainsKey("time2") ? param["time2"] : ""; string appointment = param.ContainsKey("appointment") ? param["appointment"] : ""; string appointment_time = param.ContainsKey("appointment_time") ? param["appointment_time"] : ""; string error = ""; bool flag = AddSign(out error, user1, location1, address1, time1, photo, type, state, remark, user2, location2, address2, time2, appointment, appointment_time); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_sign": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; int user1 = param.ContainsKey("user1") ? Convert.ToInt32(param["user1"]) : 0; string location1 = param.ContainsKey("location1") ? param["location1"] : ""; string address1 = param.ContainsKey("address1") ? param["address1"] : ""; string time1 = param.ContainsKey("time1") ? param["time1"] : ""; string photo = param.ContainsKey("photo") ? param["photo"] : ""; string type = param.ContainsKey("type") ? param["type"] : ""; string state = param.ContainsKey("state") ? param["state"] : ""; string remark = param.ContainsKey("remark") ? param["remark"] : ""; int user2 = param.ContainsKey("user2") ? Convert.ToInt32(param["user2"]) : 0; string location2 = param.ContainsKey("location2") ? param["location2"] : ""; string address2 = param.ContainsKey("address2") ? param["address2"] : ""; string time2 = param.ContainsKey("time2") ? param["time2"] : ""; string appointment = param.ContainsKey("appointment") ? param["appointment"] : ""; string error = ""; bool flag = UpdateSign(out error, id, user1, location1, address1, time1, photo, type, state, remark, user2, location2, address2, time2, appointment); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "delete_sign": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteSign(out error, id); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_sign": { //int leader = param.ContainsKey("leader") ? Convert.ToInt32(param["leader"]) : 0; //int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; //string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; //string identity = param.ContainsKey("identity") ? param["identity"] : ""; //string time = param.ContainsKey("time") ? param["time"] : ""; int user = 0; if (param.ContainsKey("user")) { int.TryParse(param["user"], out user); } int year = param.ContainsKey("year") ? Convert.ToInt32(param["year"]) : 0; int month = param.ContainsKey("month") ? Convert.ToInt32(param["month"]) : 0; int leader = param.ContainsKey("leader") ? Convert.ToInt32(param["leader"]) : 0; string state = param.ContainsKey("state") ? param["state"] : ""; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; string error = ""; SignInfo[] info = QuerySign(out error, leader, user, year, month, state, dep); GeneralResult <SignInfo[]> result = new GeneralResult <SignInfo[]>(); result.data = info; if (string.IsNullOrWhiteSpace(error)) { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_sign_app": { int user1 = param.ContainsKey("user1") ? Convert.ToInt32(param["user1"]) : 0; int user2 = param.ContainsKey("user2") ? Convert.ToInt32(param["user2"]) : 0; string type = param.ContainsKey("type") ? param["type"] : ""; string state = param.ContainsKey("state") ? param["state"] : ""; string time = param.ContainsKey("time") ? param["time"] : ""; string error = ""; SignInfo[] info = QuerySignForApp(out error, user1, user2, type, state, time); GeneralResult <SignInfo[]> result = new GeneralResult <SignInfo[]>(); result.data = info; if (string.IsNullOrWhiteSpace(error)) { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "add_trace_point": { double x = param.ContainsKey("x") ? Convert.ToDouble(param["x"]) : 0; double y = param.ContainsKey("y") ? Convert.ToDouble(param["y"]) : 0; int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string error = ""; bool flag = AddTracePoint(out error, x, y, user); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (string.IsNullOrWhiteSpace(error)) { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_trace": { int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string time = param.ContainsKey("time") ? param["time"] : ""; string error = ""; Trace trace = QueryTrace(out error, user, time); GeneralResult <Trace> result = new GeneralResult <Trace>(); result.data = trace; if (string.IsNullOrWhiteSpace(error)) { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "add_urinalysis": { int user1 = param.ContainsKey("user1") ? Convert.ToInt32(param["user1"]) : 0; string result = param.ContainsKey("result") ? param["result"] : ""; string remark = param.ContainsKey("remark") ? param["remark"] : ""; string photo = param.ContainsKey("photo") ? param["photo"] : ""; string error = ""; bool flag = AddUrinalysisRecord(out error, user1, result, remark, photo); GeneralResult <bool> r = new GeneralResult <bool>(); r.data = flag; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "update_urinalysis": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; int user2 = param.ContainsKey("user2") ? Convert.ToInt32(param["user2"]) : 0; string result = param.ContainsKey("result") ? param["result"] : ""; string remark = param.ContainsKey("remark") ? param["remark"] : ""; string photo = param.ContainsKey("photo") ? param["photo"] : ""; string state = param.ContainsKey("state") ? param["state"] : ""; string error = ""; bool flag = UpdateUrinalysisRecord(out error, id, user2, result, remark, photo, state); GeneralResult <bool> r = new GeneralResult <bool>(); r.data = flag; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "delete_urinalysis": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteUrinalysisRecord(out error, id); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_urinalysis": { int user = 0; if (param.ContainsKey("user")) { int.TryParse(param["user"], out user); } int year = param.ContainsKey("year") ? Convert.ToInt32(param["year"]) : 0; int month = param.ContainsKey("month") ? Convert.ToInt32(param["month"]) : 0; int leader = param.ContainsKey("leader") ? Convert.ToInt32(param["leader"]) : 0; string result = param.ContainsKey("result") ? param["result"] : ""; string state = param.ContainsKey("state") ? param["state"] : ""; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; string error = ""; UrinalysisRecord[] list = QueryUrinalysisRecord(out error, user, year, month, leader, result, state, dep); GeneralResult <UrinalysisRecord[]> r = new GeneralResult <UrinalysisRecord[]>(); r.data = list; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "add_video": { string title = param.ContainsKey("title") ? param["title"] : ""; string uploader = param.ContainsKey("uploader") ? param["uploader"] : ""; string url = param.ContainsKey("url") ? param["url"] : ""; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; string error = ""; bool flag = AddVideo(out error, title, uploader, url, dep); GeneralResult <bool> r = new GeneralResult <bool>(); r.data = flag; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "delete_video": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteVideo(out error, id); GeneralResult <bool> r = new GeneralResult <bool>(); r.data = flag; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "query_video": { string error = ""; VideoRecord[] list = QueryVideo(out error); GeneralResult <VideoRecord[]> r = new GeneralResult <VideoRecord[]>(); r.data = list; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "add_fence": { string name = param.ContainsKey("name") ? param["name"] : ""; string type = param.ContainsKey("type") ? param["type"] : ""; string extent = param.ContainsKey("extent") ? param["extent"] : ""; string error = ""; bool flag = AddFence(out error, name, type, extent); GeneralResult <bool> r = new GeneralResult <bool>(); r.data = flag; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "update_fence": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string name = param.ContainsKey("name") ? param["name"] : ""; string extent = param.ContainsKey("extent") ? param["extent"] : ""; string error = ""; bool flag = UpdateFence(out error, id, name, extent); GeneralResult <bool> r = new GeneralResult <bool>(); r.data = flag; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "delete_fence": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteFence(out error, id); GeneralResult <bool> r = new GeneralResult <bool>(); r.data = flag; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "query_fence": { string error = ""; FenceRecord[] list = QueryFence(out error); GeneralResult <FenceRecord[]> r = new GeneralResult <FenceRecord[]>(); r.data = list; if (string.IsNullOrWhiteSpace(error)) { r.success = true; } else { r.message = error; } str_result = JsonConvert.SerializeObject(r); break; } case "query_related_dep": { string error = ""; GeneralResult <ZTreeNode[]> result = new GeneralResult <ZTreeNode[]>(); int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; result.data = QueryRelatedDep(out error, id); if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "fence_relate_dep": { string error = ""; GeneralResult <bool> result = new GeneralResult <bool>(); int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string deps = param.ContainsKey("deps") ? param["deps"].ToString() : ""; result.data = FenceRelateDep(out error, id, deps); if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_region_map_data": { string regionCode = param.ContainsKey("code") ? param["code"] : ""; GeneralResult <string> result = new GeneralResult <string>(); result.data = QueryRegionMapData(regionCode); if (!string.IsNullOrWhiteSpace(result.data)) { result.success = true; } str_result = JsonConvert.SerializeObject(result); break; } case "count_active_user_by_dep": { string dep = param.ContainsKey("dep") ? param["dep"] : ""; string startTime = param.ContainsKey("start_time") ? param["start_time"] : ""; string endTime = param.ContainsKey("end_time") ? param["end_time"] : ""; GeneralResult <string> result = new GeneralResult <string>(); string str_error = ""; string data = CountActiveUser(out str_error, dep, startTime, endTime); if (str_error == "") { result.success = true; result.data = data; } else { result.message = str_error; } str_result = JsonConvert.SerializeObject(result); break; } //case "index_statistics": // { // string error = ""; // GeneralResult<string> result = new GeneralResult<string>(); // int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; // result.data = IndexStatistics(out error, dep); // if(error == "") // { // result.success = true; // } // else // { // result.message = error; // } // str_result = JsonConvert.SerializeObject(result); // break; // } default: { GeneralResult <string> result = new GeneralResult <string>("没有该方法,请检查参数"); str_result = JsonConvert.SerializeObject(result); break; } } } byte[] bytes = Encoding.UTF8.GetBytes(str_result); MemoryStream ms = new MemoryStream(bytes); return(WebOperationContext.Current.CreateStreamResponse(ms, "application/json; charset=utf-8")); } catch (Exception ex) { SystemLog.WriteErrorLog("请求失败", "2002", ex.Message, ex.StackTrace); } return(null); }
/// <summary> /// Dispatch will, given a request, return the webpage that will be shown to the user. /// </summary> /// <param name="request">The incoming HTML request, in it's entirety</param> /// <returns>The html to be sent back to the user. Additionally, it will also alter the response, if necessary</returns> public static string Dispatch(HttpListenerContext rtx) { // Check if user is logged in (via cookies?) HttpListenerRequest request = rtx.Request; HttpListenerResponse response = rtx.Response; Cookie reqLogger = request.Cookies["UserID"]; // Get URI: string path = request.RawUrl; if (path.Contains("?") || path.Length < 2) { // there will be no img path = ""; } User user = null; if (reqLogger != null) { user = new User(Convert.ToInt64(reqLogger.Value)); } if (request.ContentType != null && request.ContentType.Contains("multipart/form-data")) { MultipartParser parser = new MultipartParser(request.InputStream, "image"); if (parser.Success) { // Image file will be saved in resources/images/users/User[UID].jpg // Figure out which page user was on, engage. if (request.QueryString["dest"] != null) { switch (request.QueryString["dest"]) { case "dashboard": return(DashboardManager.Dashboard(user)); case "profile": // Save user image: user.SaveImage(parser); return(ProfileManager.ProfilePage(user)); default: return(DashboardManager.Dashboard(user)); } } else { // Just return dashboard return(DashboardManager.Dashboard(user)); } } // We have image; read! (how????) // We will return the same page, with new image! } if (request.HasEntityBody) { string input; // Read input, then dispatch accordingly using (StreamReader reader = new StreamReader(request.InputStream)) { input = reader.ReadToEnd(); NameValueCollection dict = HttpUtility.ParseQueryString(input); if (dict["submit"] != null) { // Dispatch to correct logic: switch (dict["submit"]) { case "Logout": if (request.Cookies["UserID"] != null) { // Logout user by removing UserID token: Cookie cookie = new Cookie("UserID", "-1"); cookie.Expires = DateTime.Now.AddDays(-1d); response.Cookies.Add(cookie); } return(LoginManager.Login()); case "Signup": user = new User(dict["firstName"], dict["lastName"], dict["email"], dict["password"]); user.Create(); return(LoginManager.SuccessSignup()); case "Login": try { user = new User(dict["email"], dict["password"]); Cookie logger = new Cookie("UserID", Convert.ToString(user.id)); response.Cookies.Add(logger); response.AppendHeader("dest", "dashboard"); return(DashboardManager.Dashboard(user)); } catch (InvalidPasswordException) { return(LoginManager.FailLogin()); } catch (UserNotFoundException) { return(LoginManager.FailLogin()); } case "PasswordResetRequest": // POST data will have user email. Send recovery email. PasswordReset.SendRecoveryEmail(dict["email"]); return(ResetManager.ResetPasswordSent()); case "PasswordReset": // Reset password and direct to login page // POST data will have userID in userID input. Reset the password and let the user know. long id = Convert.ToInt64(dict["userID"]); string password = dict["password"]; PasswordReset.ResetPassword(id, password); return(ResetManager.SuccessResetPassword()); default: return(LoginManager.Login()); } } else { // If string is not empty, perhaps it is a return(LoginManager.Login()); } } } else if (user == null) { // Send login page EXCEPT if requesting password reset: if (request.QueryString["ResetToken"] != null) { // Get token; search DB for hash. If it exists, show reset form string token = request.QueryString["ResetToken"]; long id = PasswordReset.GetUser(token); // Show reset form. Form will have a hidden input with UserID? return(ResetManager.CreateReset(id)); } else { return(LoginManager.Login()); } } else if (request.QueryString["dest"] != null) { switch (request.QueryString["dest"]) { case "dashboard": return(DashboardManager.Dashboard(user)); case "profile": return(ProfileManager.ProfilePage(user)); default: return(DashboardManager.Dashboard(user)); } } else if (path.Length != 0) { // Check if user is allowed to access // Serve back whatever's at the path (will be image): byte[] buffer = File.ReadAllBytes(WebServer.GeneratePath(path)); response.ContentLength64 = buffer.Length; using (Stream resp = response.OutputStream) { resp.Write(buffer, 0, buffer.Length); } return(""); } else { // If logged in (but no request), just send back home page: return(DashboardManager.Dashboard(user)); } }
/// <summary> /// 上传特巡图片 /// </summary> /// <param name="data"></param> /// <returns></returns> public Stream UploadImage(Stream data) { ResUploadImage response = new ResUploadImage(); MemoryStream source = new MemoryStream(); //FileStream fst = new FileStream("uploaddata.txt",FileMode.Open,FileAccess.ReadWrite); try { data.CopyTo(source); source.Position = 0; ReqUploadImage req = new ReqUploadImage(); List <MultipartParser> list = new List <MultipartParser>(); MultipartParser parser = new MultipartParser(source, 0); while (parser.Success) { list.Add(parser); int startPoint = parser.EndPoint + 2; source.Position = startPoint; parser = new MultipartParser(source, startPoint); } //保存图片 List <Response.Entity.PicInfo> imageList = new List <Response.Entity.PicInfo>(); if (list != null && list.Count > 0) { string dirName = GenerateDirName(DateTime.Now.Millisecond); req.user_id = Encoding.UTF8.GetString(list[0].FileContents); req.token = Encoding.UTF8.GetString(list[1].FileContents); Console.WriteLine(req.user_id); Console.WriteLine(req.token); if (req.user_id != null && req.user_id != String.Empty && req.token != null && req.token != String.Empty) { //用于判断图片是否全部保存成功 bool saveSuccess = true; for (int i = 2; i < list.Count; i++) { MultipartParser item = list[i]; Console.WriteLine(item.Filename + " --- " + item.FileContents.Length); Response.Entity.PicInfo image = new Response.Entity.PicInfo(); string filename = Save2File(dirName, item.FileContents); if (filename == String.Empty) { //保存失败 结束后续操作 LogWriter.MyLog.Error(dirName + "保存图片未获得文件名称"); saveSuccess = false; break; } image.image_name = item.Filename; image.pic_url = filename; imageList.Add(image); } response.model_list = imageList; response.dir_name = dirName; if (saveSuccess) { response.SetSuccess(); } else { response.SetFailed(); } } } #region 注释 ////重置流位置 //source.Position = 0; //BinaryReader br = new BinaryReader(source, Encoding.UTF8); //byte[] dataSource = source.ToArray(); //int intBoundary = 0; ////索引值 //for (int i = 0; i < dataSource.Length - 2; i++) //{ // if (dataSource[i] == 13 && dataSource[i + 1] == 10) // { // intBoundary = i + 1; // break; // } //} ////获得分隔符 //source.Position = 0; //byte[] boundary = br.ReadBytes(intBoundary + 1); ////头部数据 //int bodyStart = 0; //for (int i = intBoundary + 1; i < dataSource.Length - 2; i++) //{ // if (dataSource[i] == 13 && dataSource[i + 1] == 10 && dataSource[i + 2] == 13 && dataSource[i + 3] == 10) // { // bodyStart = i + 3; // break; // } //} ////解析头部数据 //source.Position = intBoundary + 1; //byte[] hdata = br.ReadBytes(bodyStart - 4 - intBoundary); //string sdata = Encoding.UTF8.GetString(hdata); ////获取下一个分隔符位置 来取得数据体范围 //int bodyEnd = 0; //source.Position = bodyStart + 1; ////最后一个分隔符多了一个\r\n //long dataEnd = dataSource.Length - 2 - boundary.Length; //最后一个分隔符 除去 //for (int i = bodyStart + 1; i < dataEnd; i++) //{ // byte[] temp = br.ReadBytes(boundary.Length); // if (temp == boundary) // { // bodyEnd = i - 1; // break; // } //} ////表单数据体 //source.Position = bodyStart + 1; //byte[] formData = br.ReadBytes(bodyEnd - bodyStart); //int nextStart = bodyEnd + boundary.Length + 1; ////图片数据 //getImageData(source, nextStart); #endregion } catch (Exception ex) { Console.WriteLine(ex.Message); #region 日志输出 CommonInfo.Error("上传图片发生错误" + ex.Message); #endregion } source.Close(); //将消息序列化为Json格式数据 DataContractJsonSerializer obj2Json = new DataContractJsonSerializer(typeof(ResUploadImage)); MemoryStream ms = new MemoryStream(); obj2Json.WriteObject(ms, response); //注意一定要设置流的位置到开始位置,否则没有消息输出 ms.Position = 0; return(ms); }
public Arena.Services.Contracts.ModifyResult UpdateSmallGroupPhoto(System.IO.Stream stream, int id) { try { Arena.SmallGroup.Group group = new Arena.SmallGroup.Group(id); Boolean accessDenied = false; // If this person isn't the outright leader and they don't have edit access if (group.Leader.PersonID != ArenaContext.Current.Person.PersonID && RestApi.GroupClusterOperationAllowed(ArenaContext.Current.Person.PersonID, group.GroupClusterID, OperationType.Edit) == false) { accessDenied = true; // Do a deeper dive into each member of the group foreach (GroupMember gm in group.Members) { if (gm.Active && gm.Role.Value == "Leader") { accessDenied = false; break; } } } if (accessDenied) { throw new Exception("Access denied."); } MultipartParser parser = new MultipartParser(stream); if (parser.Success) { // Make sure this is a real image MemoryStream ms = new MemoryStream(parser.FileContents); String myStream = Encoding.ASCII.GetString(ms.ToArray()); Image image = Image.FromStream(ms); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo codec = codecs.First(c => c.FormatID == image.RawFormat.Guid); // If we have an existing image, delete it if (group.ImageBlob.BlobID > 0) { group.ImageBlob.Delete(); } // Create a new file Utility.ArenaImage arenaImage = new Utility.ArenaImage(); // Update everything arenaImage.ByteArray = parser.FileContents; arenaImage.MimeType = codec.MimeType; arenaImage.OriginalFileName = Path.GetFileNameWithoutExtension(parser.Filename) + "." + codec.FormatDescription.ToLower().Replace("jpeg", "jpg"); arenaImage.FileExtension = codec.FormatDescription.ToLower().Replace("jpeg", "jpg"); // Save the file group.ImageBlob = arenaImage; group.ImageBlob.Save(ArenaContext.Current.User.Identity.Name); group.Save(ArenaContext.Current.User.Identity.Name); } return new Services.Contracts.ModifyResult() { Link = Contracts.SmallGroupMapper.getImageThumbnailUrl(group.ImageBlob), Successful = true.ToString() }; } catch (Exception ex) { return new Services.Contracts.ModifyResult() { Successful = false.ToString(), ErrorMessage = string.Format("{0} - {1}", ex.GetType().ToString(), ex.Message) }; } }
private bool ParsePost(HTTPRequest request, Socket client) { if (!request.headers.ContainsKey("Content-Length")) { return(true); } int bodySize; var lenStr = request.headers["Content-Length"]; if (lenStr.Contains("\0")) { throw new NullByteInjectionException(); } int.TryParse(lenStr, out bodySize); if (bodySize < 0 || bodySize > Settings.MaxPostSizeInBytes) { return(false); } if (bodySize > 0 && request.bytes == null) { return(false); } if (bodySize > request.bytes.Length) { return(false); } var contentTypeHeader = request.headers.ContainsKey("Content-Type") ? request.headers["Content-Type"] : "application/x-www-form-urlencoded; charset=UTF-8"; if (contentTypeHeader.Contains("\0")) { throw new NullByteInjectionException(); } contentTypeHeader = contentTypeHeader.ToLowerInvariant(); if (contentTypeHeader.StartsWith("multipart/form-data")) { var parser = new MultipartParser(new MemoryStream(request.bytes), (key, val) => { var value = val.UrlDecode(); if (value.Contains("\0")) { throw new NullByteInjectionException(); } request.args[key] = value; }); if (parser.Success) { request.uploads.Add(new FileUpload(parser.Filename, parser.ContentType, parser.FileContents)); } } else if (contentTypeHeader.StartsWith("application/x-www-form-urlencoded")) { var encoding = System.Text.Encoding.UTF8; //request.headers["Content-Encoding"] var requestBody = encoding.GetString(request.bytes); // TODO: implement multipart/form-data parsing // example available here: http://stackoverflow.com/questions/5483851/manually-parse-raw-http-data-with-php // verify there is data to parse if (String.IsNullOrWhiteSpace(requestBody)) { return(true); } // define a character for KV pairs var kvpSeparator = new[] { '=' }; // Split the request body into key-value pair strings var keyValuePairStrings = requestBody.Split('&'); foreach (var kvps in keyValuePairStrings) { // Skip KVP strings if they are empty if (string.IsNullOrWhiteSpace(kvps)) { continue; } // Split by the equals char into key values. // Some KVPS will have only their key, some will have both key and value // Some other might be repeated which really means an array var kvpsParts = kvps.Split(kvpSeparator, 2); // We don't want empty KVPs if (kvpsParts.Length == 0) { continue; } // Decode the key and the value. Discard Special Characters var key = WebUtility.UrlDecode(kvpsParts[0]); if (key.Contains("\0")) { throw new NullByteInjectionException(); } if (kvpsParts.Length == 1 && keyValuePairStrings.Length == 1) { request.postBody = key; break; } var value = kvpsParts.Length >= 2 ? System.Net.WebUtility.UrlDecode(kvpsParts[1]) : ""; // Simply set the key to the parsed value value = value.UrlDecode(); if (value.Contains("\0")) { throw new NullByteInjectionException(); } request.args[key] = value; } } else { var encoding = System.Text.Encoding.UTF8; //request.headers["Content-Encoding"] request.postBody = encoding.GetString(request.bytes); if (request.postBody.Contains("\0")) { throw new NullByteInjectionException(); } } return(true); }
public static UploadPictureResponse uploadPhotoImplementation(Stream file, string token, string accountId) { if (String.IsNullOrWhiteSpace(token)) { return(new UploadPictureResponse { message = "Gym not found.", status = 404, success = false, }); } int accountIdAsInt; if (String.IsNullOrWhiteSpace(accountId) || !Int32.TryParse(accountId, out accountIdAsInt)) { return(new UploadPictureResponse { message = "Gym not found.", status = 404, success = false, }); } var parser = new MultipartParser(file); using (var db = new UniversalGymEntities()) { var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == token && a.GymId == accountIdAsInt); if (gym == null) { new UploadPictureResponse { message = "Gym not found.", status = 404, success = false, }; } if (gym.GymPhotoGalleries.Count >= 8) { return(new UploadPictureResponse { message = "You can only upload up to 8 images.", status = 404, success = false }); } if (parser.Success) { // Make sure really is image and the kind we want string[] supportedMimeTypes = { "images/png", "image/png", "image/jpeg", "images/jpeg", "image/jpg", "images/jpg" }; if (!supportedMimeTypes.Contains(parser.ContentType.ToString().ToLower())) { return(new UploadPictureResponse { message = "Image needs to be .png or .jpg", status = 404, success = false }); } var megabyte = 1024; var fileSizeLimit = megabyte * 2; if (parser.FileContents.Length < fileSizeLimit) { return(new UploadPictureResponse { message = "Image too large", status = 404, success = false }); } var picture = new Data.GymPhotoGallery { GymId = gym.GymId, IsCoverPhoto = false }; db.GymPhotoGalleries.Add(picture); var filename = gym.GymId + "_" + Guid.NewGuid(); var storageAccount = CloudStorageAccount.Parse(Constants.BlobStorageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer blobContainer = blobClient.GetContainerReference(Constants.GymPicturesBlobContainerName); CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename); blob.Properties.ContentType = parser.ContentType; blob.UploadFromByteArrayAsync(parser.FileContents, 0, parser.FileContents.Length); // the magical url to the picture var url = blob.Uri.ToString(); picture.Photo = url; // if no other photos, set isCoverPhoto to true var hasCoverPhoto = db.GymPhotoGalleries.SingleOrDefault(a => a.GymId == gym.GymId && a.IsCoverPhoto == true); if (hasCoverPhoto == null) { picture.IsCoverPhoto = true; } db.SaveChanges(); var uploadedPhoto = new pictureResult { url = picture.Photo, pictureId = picture.GymPhotoGalleryId, isCoverPhoto = picture.IsCoverPhoto, }; // return back new url return(new UploadPictureResponse { status = 200, picture = uploadedPhoto, success = true, message = "Success!" }); } else { return(new UploadPictureResponse { status = 500, success = false, message = "Not able to parse file" }); } } }