public void Deny_Unrestricted() { Assert.IsNotNull(coll.AllKeys, "AllKeys"); coll.CopyTo(new object[0], 0); Assert.IsNull(coll.Get("mono"), "Get(string)"); Assert.IsNull(coll["mono"], "this[string]"); try { Assert.IsNull(coll[0], "this[int]"); } catch (ArgumentOutOfRangeException) { // normal (can't avoid it) } try { Assert.IsNull(coll.GetKey(0), "GetKey(int)"); } catch (ArgumentOutOfRangeException) { // normal (can't avoid it) } try { Assert.IsNull(coll.Get(0), "Get(int)"); } catch (ArgumentOutOfRangeException) { // normal (can't avoid it) } }
public override HttpPostedFileBase Get(int index) { HttpPostedFile file = _collection.Get(index); if (file == null) { return(null); } return(new HttpPostedFileWrapper(file)); }
string UploadImg(string filename, string ordernum) { string modelimgurl = string.Empty; #region -----------------上传图片------------------- HttpFileCollection files = HttpContext.Current.Request.Files; //检查文件扩展名字 HttpPostedFile postedFile = files.Get(filename); string fileName, fileExtension, file_id; //取出精确到毫秒的时间做文件的名称 fileName = System.IO.Path.GetFileName(postedFile.FileName); fileExtension = System.IO.Path.GetExtension(fileName); file_id = filename + ordernum + fileExtension.ToLower(); if (fileName != "" && fileName != null && fileName.Length > 0) { fileExtension = System.IO.Path.GetExtension(fileName); string saveurl; modelimgurl = "Active/"; saveurl = modelimgurl; saveurl = Server.MapPath(saveurl); if (!Directory.Exists(saveurl)) { Directory.CreateDirectory(saveurl); } int length = postedFile.ContentLength; postedFile.SaveAs(saveurl + file_id); modelimgurl = modelimgurl + file_id; } #endregion return(modelimgurl); }
public void SaveUploadedFile(HttpFileCollection httpFileCollection) { bool isSavedSuccessfully = true; string fName = ""; foreach (string fileName in httpFileCollection) { HttpPostedFile file = httpFileCollection.Get(fileName); //Save file content goes here fName = file.FileName; if (file != null && file.ContentLength > 0) { var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\"))); string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath"); var fileName1 = Path.GetFileName(file.FileName); bool isExists = System.IO.Directory.Exists(pathString); if (!isExists) { System.IO.Directory.CreateDirectory(pathString); } var path = string.Format("{0}\\{1}", pathString, file.FileName); file.SaveAs(path); } } //if (isSavedSuccessfully) //{ // return Json(new { Message = fName }); //} //else //{ // return Json(new { Message = "Error in saving file" }); //} }
private void LoadUpfiles() { if (fileKeys == null || fileKeys.Count <= 0) { throw new Exception("上传资源不能为空"); } if (fileKeys.Count > ResxConfigManager.RESX_MAX_COUNT) { throw new Exception("上传资源数量超过大小"); } files = new List <HttpPostedFile>(fileKeys.Count); foreach (string item in fileKeys) { HttpPostedFile f = fileKeys.Get(item); string ext = Path.GetExtension(f.FileName).ToLower(); if (!this.resxModel.ResxTypes.Contains(ext)) { throw new Exception("上传包含未知资源类型"); } if (f.InputStream.Length > this.resxModel.ResxSize && this.resxModel.ResxSize > 0) { throw new Exception("上传资源超过大小"); } files.Add(f); } }
public string SaveUploadedFile(HttpFileCollection httpFileCollection) { foreach (string fileName in httpFileCollection) { var file = httpFileCollection.Get(fileName); // Save file content goes here if (file == null || file.ContentLength == 0) { continue; } string path = this.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\")) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\Temp\", path); } else { path = string.Format(CultureInfo.InvariantCulture, @"{0}Temp\", path); } path = string.Format(CultureInfo.InvariantCulture, "{0}{1}", path, file.FileName); file.SaveAs(path); this.ReadXlsx(path, this.instance.Config.ConnectionString); return(path); } return(string.Empty); }
protected void Page_Load(object sender, EventArgs e) { // check required fields if (String.IsNullOrEmpty(AllowedExtensions)) { throw new Exception("AllowedExtensions is a required attribute for the FileUploader component."); return; } HttpFileCollection uploadFiles = Request.Files; HttpPostedFile postedFile = uploadFiles.Get(0); // access the uploaded file's content in-memory System.IO.Stream inStream = postedFile.InputStream; byte[] fileData = new byte[postedFile.ContentLength]; inStream.Read(fileData, 0, postedFile.ContentLength); // specify the path where we're going to save the uploaded file string fileName = new FileInfo(postedFile.FileName).Name; // this prevents the full path being returned with IE string pathToCheck = UploadFolderPath + fileName; // check the extension. This shouldn't fail, if the client-side portion was set up properly // to whitelist the same extensions string extension = System.IO.Path.GetExtension(fileName).ToLowerInvariant(); extension = extension.Substring(1); // bizarrely, the above function returns the dot + extension string[] validExtensions = AllowedExtensions.Split(','); if (!validExtensions.Contains(extension)) { // this could also maybe return the info to the client throw new Exception("Invalid file extension: " + extension); } else { // some additional logic to prevent filename collisions if (System.IO.File.Exists(pathToCheck)) { string tempfileName = ""; int counter = 2; while (System.IO.File.Exists(pathToCheck)) { tempfileName = counter.ToString() + fileName; pathToCheck = UploadFolderPath + tempfileName; counter++; } fileName = tempfileName; } // save the frickin' file already postedFile.SaveAs(UploadFolderPath + fileName); // we have to output the name plain-text because older IE can't handle the JSON headers for // iframe-uploaded files Response.Clear(); Response.ContentType = "text/plain"; Response.Write("filename:" + fileName); Response.End(); } }
/// <summary> /// 普通形式文件上传 /// </summary> /// <param name="context">HttpContext</param> /// <param name="disposition">HTTP_CONTENT_DISPOSITION</param> /// <param name="localFileName">原始文件名</param> /// <returns>文件流</returns> private byte[] HanlderNormalUploadType(HttpContext context, string disposition, out string localFileName) { localFileName = string.Empty; byte[] _fileBuffer = null; if (disposition == null) { HttpFileCollection _filecollection = context.Request.Files; HttpPostedFile _postedfile = _filecollection.Get(this.FileInputName); localFileName = Path.GetFileName(_postedfile.FileName); _fileBuffer = new byte[_postedfile.ContentLength]; using (Stream stream = _postedfile.InputStream) { stream.Read(_fileBuffer, 0, _postedfile.ContentLength); if (_filecollection != null) { _filecollection = null; } } } return(_fileBuffer); }
private void HandleSave(HttpContext context) { HttpFileCollection fs = context.Request.Files; Dictionary <string, byte[]> files = new Dictionary <string, byte[]>(); var id = context.Request.Form["id"]; var email = context.Request.Form["email"]; var comment = context.Request.Form["comment"]; //foreach (string file in fs) //{ // HttpPostedFile mainf = fs.Get(file); // files.Add(file, mainf.ToByteArray()); //} for (int i = 0; i < fs.Count; i++) { HttpPostedFile mainf = fs.Get(i); files.Add(mainf.FileName, mainf.ToByteArray()); } bool result = presenter.SaveComment(id, email, comment, files); if (result) { context.Response.Write("success"); } else { context.Response.Write("failed"); } }
// Works all around! public string TransferFile() { HttpContext postedContext = HttpContext.Current; String sOut = ""; // Get other parameters in request using Params.Get String fileName = postedContext.Request.Params.Get("FileName"); String fileIdentifier = postedContext.Request.Params.Get("FileIdentifier"); String applnId = postedContext.Request.Params.Get("ApplnId"); String user = postedContext.Request.Params.Get("UserId"); String password = postedContext.Request.Params.Get("Password"); String fileNo = postedContext.Request.Params.Get("FileNo"); String fileRow = postedContext.Request.Params.Get("FileRowSrno"); String remark = postedContext.Request.Params.Get("Remark"); String image1 = "undefined", image2 = "undefined", image3 = "undefined", image4 = "undefined", image5 = "undefined"; HttpFileCollection FilesInRequest = postedContext.Request.Files; for (int i = 0; i < FilesInRequest.AllKeys.Length; i++) { // Loop through to get all files in the request HttpPostedFile item = FilesInRequest.Get(i); string filename = item.FileName; byte[] fileBytes = new byte[item.ContentLength]; item.InputStream.Read(fileBytes, 0, item.ContentLength); var appData = Server.MapPath("~/App_Data/"); var file = Path.Combine(appData, Path.GetFileName(filename)); File.WriteAllBytes(file, fileBytes); switch (i) { case 0: image1 = filename; break; case 1: image2 = filename; break; case 2: image3 = filename; break; case 3: image4 = filename; break; case 4: image5 = filename; break; } } sOut = "Image1 - " + image1 + "Image2 - " + image2 + "Image3 - " + image3 + "Image4 - " + image4 + "Image5 - " + image5; return(sOut); }
public void SaveUploadedFile(HttpFileCollection httpFileCollection, string foldername) { foreach (string fileName in httpFileCollection) { HttpPostedFile file = httpFileCollection.Get(fileName); UploadAttachment(file, foldername); } }
private void Page_Load(Object sender, EventArgs e) { // <Snippet1> HttpFileCollection MyFileColl = Request.Files; HttpPostedFile MyPostedMember = MyFileColl.Get(0); String MyFileName = MyPostedMember.FileName; // </Snippet1> }
public void ProcessRequest(HttpContext context) { string rtnjson = string.Empty; Dictionary <string, string> dic = null; var ser = new JavaScriptSerializer(); try { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; HttpFileCollection fileCollects = context.Request.Files; List <HttpPostedFile> files = new List <HttpPostedFile>(); List <string> filePaths = new List <string>(); if (fileCollects.Count > 0) { DateTime theDate = DateTime.Now; string dt = theDate.Year.ToString() + theDate.Month.ToString() + theDate.Day.ToString() + theDate.Hour.ToString() + theDate.Minute.ToString() + theDate.Second.ToString(); string filePath = HttpContext.Current.Server.MapPath("\\file" + "\\" + dt) + "\\"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } for (int i = 0; i < fileCollects.Count; i++) { HttpPostedFile file = fileCollects.Get(i); string fileExtension = Path.GetExtension(file.FileName); var path = filePath + file.FileName.Replace(fileExtension, "") + fileExtension;// + DateTime.Now.ToString("yyyyMMddhhmmss") file.SaveAs(path); filePaths.Add(path); } } else { dic = new Dictionary <string, string>(); dic.Add("Success", "false"); dic.Add("Message", "请选择需要上传的文件"); rtnjson = ser.Serialize(dic); context.Response.Write(rtnjson); } object resultObject = new { Success = true, Message = "文件保存成功", Filepath = filePaths }; rtnjson = ser.Serialize(resultObject); context.Response.Write(rtnjson); } catch (Exception exception) { dic = new Dictionary <string, string>(); dic.Add("Success", "false"); dic.Add("Message", exception.Message); rtnjson = ser.Serialize(dic); context.Response.Write(rtnjson); } }
/// <summary> /// Save all uploaded image /// </summary> /// <param name="httpFileCollection"></param> public void PostRecordedAudioVideo(HttpFileCollection httpFileCollection) { //bool isSavedSuccessfully = true; //string fName = ""; foreach (string fileName in httpFileCollection) { HttpPostedFile file = httpFileCollection.Get(fileName); UploadAttachment(file); } }
public static IEnumerable <PostedFile> LoadRespondentFiles(HttpFileCollection fileCollection) { for (int i = 0; i < fileCollection.Count; i++) { HttpPostedFile file = fileCollection.Get(i); PostedFile postedFile = new PostedFile { FileName = file.FileName, InputStream = file.InputStream }; RespondentFiles.Add(postedFile); yield return(postedFile); } }
/// <summary> /// 批量上传文件 /// </summary> /// <param name="fileCollection">要上传的文件对象</param> /// <param name="FilePath">文件保存路径(相对网站根目录路径)</param> /// <param name="AllowFileType">允许上传的文件类型</param> /// <returns>返回上传状态及上传后的新文件路径</returns> public static UploadStatus Upload(HttpFileCollection fileCollection, string FilePath, string[] AllowFileType) { var US = new UploadStatus(); if (fileCollection.Count <= 0) { US.Status = false; US.Msg = "没有提交图片."; return(US); } for (int i = 0; i < fileCollection.Count; i++) { US = Upload(fileCollection.Get(i), FilePath, AllowFileType); if (!US.Status) { US.Msg = "图片[" + fileCollection.Get(i).FileName + "]上传失败!"; US.Status = false; break; } } return(US); }
public string UploadVideo(HttpFileCollection video) { if (video.Count <= 0) { return(null); } var fileName = Path.GetFileName(video.Get(0).FileName); var path = Path.Combine(Server.MapPath("~/Content/assets/uploads"), fileName); // save video here video[0].SaveAs(path); return(fileName); }
/// <summary> /// Save all uploaded image /// </summary> /// <param name="httpFileCollection"></param> public string SaveUploadedFile(HttpFileCollection httpFileCollection) { String response = "{\"uploaded\": 1,\"fileName\": \"**filename**\",\"url\": \"/TaskAttachments/**filename**\"}|"; //bool isSavedSuccessfully = true; //string fName = ""; foreach (string fileName in httpFileCollection) { HttpPostedFile file = httpFileCollection.Get(fileName); response = response.Replace("**filename**", UploadAttachment(file)); } return(response); }
public void ProcessRequest(HttpContext context) { HttpFileCollection httpFileCollection = context.Request.Files; string fName = ""; string jsondata = "../Images/Code/"; string filename = context.Request["filename"] + ".jpg"; try { foreach (string fileName in httpFileCollection) { HttpPostedFile file = httpFileCollection.Get(fileName); //Save file content goes here fName = file.FileName; if (file != null && file.ContentLength > 0) { var originalDirectory = new DirectoryInfo(string.Format("{0}Images", context.Server.MapPath("~/"))); string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "Code"); var fileName1 = Path.GetFileName(file.FileName); bool isExists = System.IO.Directory.Exists(pathString); if (!isExists) { System.IO.Directory.CreateDirectory(pathString); } FileInfo fileinfo = new FileInfo(file.FileName); //string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg"; var path = string.Format("{0}\\{1}", pathString, filename); file.SaveAs(path); jsondata += filename; } } } catch (Exception ex) { jsondata = ex.Message; //throw; } context.Response.ContentType = "text/plain"; //context.Response.Write(jsondata); context.Response.Write("{\"imgpath\":\"" + jsondata + "\"}"); }
public void SaveUploadedFile(HttpFileCollection httpFileCollection) { int i = 0; string Variable = Session["Usuario"].ToString(); // bool isSavedSuccessfully = true; string fName = ""; foreach (string fileName in httpFileCollection) { //while (i <= 2) //{ HttpPostedFile file = httpFileCollection.Get(fileName); //Save file content goes here fName = file.FileName; if (file != null && file.ContentLength > 0) { var originalDirectory = new DirectoryInfo(Server.MapPath("~/LibrosPortadas/" + Variable + "/")); if (!Directory.Exists(originalDirectory.ToString())) { Directory.CreateDirectory(originalDirectory.ToString()); } string pathString = originalDirectory.ToString(); var FileNameVerify = Path.GetFileName(file.FileName); //Lo estoy usando para verificar algo var fileName1 = Path.GetFileNameWithoutExtension(file.FileName); //Cambié esta instrucción para obtener solo el nombre del archivo, sin la extensión. if (FileNameVerify.Contains(".pdf") || FileNameVerify.Contains(".PDF")) { //Solo el pdf necesitamos encriptar string encryptedName = fileName1 + "_encrypted"; //Se asigna el nombre que tendrá el archivo ya encriptado string pathDestino = pathString + encryptedName; //Se combinan las rutas para indicar en dónde se guardará el archivo encriptado EncryptFile(file, pathDestino); //Llamada al método para encriptar archivo Session["LibroFisico"] = Variable + "/" + fileName1; } else { Session["ImagenPortada"] = Variable + "/" + FileNameVerify.ToString(); var path = string.Format("{0}\\{1}", pathString, file.FileName); file.SaveAs(path); //Guarda el archivo físico original en servidor } //Después de encriptar... sería óptimo borrar el archivo original? O sería mucho uso de memoria? Por el hecho de leer y escribir en servidor. } i++; //} } }
public async Task <string> UploadPublicPictureWithGUID() { HttpFileCollection filecol = HttpContext.Current.Request.Files; HttpPostedFile a = filecol.Get("FileUpload"); PictureValidation.GetInstance().CompleteValidations(filecol); string uploadPath = PictureHandling.GetInstance().HandlingUpdatePublicDirectories(); Guid Guided = Guid.NewGuid(); uploadPath += "\\" + Guided.ToString("N") + ".jpg"; //a.SaveAs(uploadPath); MemoryStream mss = new MemoryStream(); a.InputStream.CopyTo(mss); using (mss) { ////with no compress; //Image img = System.Drawing.Image.FromStream(ms); //img.Save(withoutextension + "-th" + ".jpg"); //with compress; Image img = System.Drawing.Image.FromStream(mss); EncoderParameters eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L); string mimetype = GetMimeType(new System.IO.FileInfo(uploadPath).Extension); ImageCodecInfo ici = GetEncoderInfo(mimetype); img.Save(uploadPath, ici, eps); } return(JsonConvert.SerializeObject(new FileResult { FileName = Path.GetFileName(uploadPath), FileLength = new FileInfo(uploadPath).Length, LocalFilePath = Cryptography.Encrypt(uploadPath), })); }
/// <summary> /// Creates a TempFileCollection from a collection of files uploaded through HTTP. The uploaded files are saved to /// a temporary folder. Duplicate file names are handled. /// </summary> public TempFileCollection(HttpFileCollection files, int maxFileSizeInBytes) { if (files == null || files.Count == 0) { return; } for (int index = 0; index < files.Count; index++) { HttpPostedFile file = files.Get(index); if (!string.IsNullOrEmpty(file.FileName) && (maxFileSizeInBytes == 0 || file.ContentLength <= maxFileSizeInBytes)) { string filePath = GetNewTempFilePath(file.FileName); file.SaveAs(filePath); _filePaths.Add(filePath); } } }
public void PopulateTree(CompositeNode root, HttpFileCollection fileCollection) { foreach (String key in fileCollection.Keys) { if (key == null) { continue; } HttpPostedFile value = fileCollection.Get(key); if (value == null) { continue; } ProcessNode(root, typeof(HttpPostedFile), key, value); } }
public IEnumerable <IPostedFile> GetPostedFiles() { HttpFileCollection files = HttpContext.Current.Request.Files; if (files.Count == 0) { return new IPostedFile[] { } } ; List <HttpPostedFileWrapper> results = new List <HttpPostedFileWrapper>(); for (int i = 0; i < files.Count; i++) { results.Add(new HttpPostedFileWrapper(files.Get(i))); } return(results); } }
public static string[] GetEmptyFileNames(HttpFileCollection files) { if (files == null || files.Count == 0) { return(null); } var empty = new ArrayList(); for (var index = 0; index < files.Count; index++) { var file = files.Get(index); if (file.ContentLength == 0 && !String.IsNullOrEmpty(file.FileName)) { empty.Add(file.FileName); } } return(empty.Count == 0 ? null : (string[])empty.ToArray(typeof(string))); }
public static string[] GetDisallowedFileNames(HttpFileCollection files) { if (files == null || files.Count == 0) { return(null); } var disallowed = new ArrayList(); for (var index = 0; index < files.Count; index++) { var file = files.Get(index); if (!IsAttachmentExtensionAllowed(file.FileName)) { disallowed.Add(file.FileName); } } return(disallowed.Count == 0 ? null : (string[])disallowed.ToArray(typeof(string))); }
// Works all around! public string TransferFile() { HttpContext postedContext = HttpContext.Current; // Get other parameters in request using Params.Get String fileName = postedContext.Request.Params.Get("FileName"); String fileIdentifier = postedContext.Request.Params.Get("FileIdentifier"); String user = postedContext.Request.Params.Get("UserId"); HttpFileCollection FilesInRequest = postedContext.Request.Files; for (int i = 0; i < FilesInRequest.AllKeys.Length; i++) { // Loop through to get all files in the request HttpPostedFile item = FilesInRequest.Get(i); string filename = item.FileName; byte[] fileBytes = new byte[item.ContentLength]; item.InputStream.Read(fileBytes, 0, item.ContentLength); var appData = Server.MapPath("~/App_Data"); var file = Path.Combine(appData, Path.GetFileName(filename)); File.WriteAllBytes(file, fileBytes); } return("Superb, saved"); }
public void ProcessRequest(HttpContext context) { try { context.Response.Clear(); context.Response.ContentType = "text/plain"; context.Response.Charset = "UTF-8"; // 初始化一大堆变量 string inputname = "file"; //表单文件域name string attachdir = "/Picture/photo"; // 上传文件保存路径,结尾不要带/ string upext = "jpg,jpeg,gif,png"; // 上传扩展名jpg,png,gif,jpeg string oldpic = context.Request.QueryString["oldpic"]; //原图片路径 byte[] file; // 统一转换为byte数组处理 string localname = ""; string disposition = context.Request.ServerVariables["HTTP_CONTENT_DISPOSITION"]; if (disposition != null)// HTML5上传 { file = context.Request.BinaryRead(context.Request.TotalBytes); localname = context.Server.UrlDecode(System.Text.RegularExpressions.Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名 } else { HttpFileCollection filecollection = context.Request.Files; HttpPostedFile postedfile = filecollection.Get(inputname); // 读取原始文件名 localname = postedfile.FileName; // 初始化byte长度. file = new Byte[postedfile.ContentLength]; // 转换为byte类型 System.IO.Stream stream = postedfile.InputStream; stream.Read(file, 0, postedfile.ContentLength); stream.Close(); filecollection = null; } if (file.Length == 0) { throw new Exception(JsonConvert.SerializeObject(new { state = 0, msg = "无数据提交" })); } else { if (file.Length > 30720) { throw new Exception(JsonConvert.SerializeObject(new { state = 0, msg = "文件大小超过30KB" })); } else { string attach_dir, attach_subdir, filename, extension, target; extension = GetFileExt(localname);// 取上载文件后缀名 if (("," + upext + ",").IndexOf("," + extension + ",") < 0) { throw new Exception(JsonConvert.SerializeObject(new { state = 0, msg = "上传文件扩展名必需为:" + upext })); } else { if (Utility.employeeLogin.isLogin) { attach_subdir = DateTime.Now.ToString("yyMMdd"); attach_dir = attachdir + "/" + attach_subdir + "/"; // 生成随机文件名 Random random = new Random(DateTime.Now.Millisecond); filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension; target = attach_dir + filename; try { CreateFolder(context.Server.MapPath(attach_dir)); //保存图片 System.IO.FileStream fs = new System.IO.FileStream(context.Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(file, 0, file.Length); fs.Flush(); fs.Close(); } catch (Exception ex) { throw new Exception(JsonConvert.SerializeObject(new { state = 0, msg = ex.Message })); } if (oldpic != "" && oldpic != null) { Common.DirFile.DeleteFile(oldpic);//删除原来图片 } BLL.account.employeeBLL.updPhoto(target, Utility.employeeLogin.eid); context.Response.Write(JsonConvert.SerializeObject(new { state = 1, msg = target })); } else { throw new Exception(JsonConvert.SerializeObject(new { state = 4001, msg = "没有访问权限" })); } } } } file = null; } catch (Exception m) { context.Response.Write(m.Message); } finally { context.Response.End(); } }
public void ProcessRequest(HttpContext context) { context.Response.Charset = "UTF-8"; byte[] file; string localFileName = string.Empty; string err = string.Empty; string subFolder = string.Empty; string fileFolder = string.Empty; string filePath = string.Empty;; var disposition = context.Request.ServerVariables["HTTP_CONTENT_DISPOSITION"]; if (disposition != null) { // HTML5上传 file = context.Request.BinaryRead(context.Request.TotalBytes); localFileName = Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value;// 读取原始文件名 } else { HttpFileCollection filecollection = context.Request.Files; HttpPostedFile postedfile = filecollection.Get(this.FileInputName); // 读取原始文件名 localFileName = Path.GetFileName(postedfile.FileName); // 初始化byte长度. file = new Byte[postedfile.ContentLength]; // 转换为byte类型 System.IO.Stream stream = postedfile.InputStream; stream.Read(file, 0, postedfile.ContentLength); stream.Close(); filecollection = null; } var ext = localFileName.Substring(localFileName.LastIndexOf('.') + 1).ToLower(); if (file.Length == 0) { err = "无数据提交"; } else if (file.Length > this.MaxFilesize) { err = "文件大小超过" + this.MaxFilesize + "字节"; } else if (!AllowExt.Contains(ext)) { err = "上传文件扩展名必需为:" + string.Join(",", AllowExt); } else { var folder = context.Request["subfolder"] ?? "default"; var uploadFolderConfig = UploadConfigContext.UploadConfig.UploadFolders.FirstOrDefault(u => string.Equals(folder, u.Path, StringComparison.OrdinalIgnoreCase)); var dirType = uploadFolderConfig == null ? DirType.Day : uploadFolderConfig.DirType; //根据配置里的DirType决定子文件夹的层次(月,天,扩展名) switch (dirType) { case DirType.Month: subFolder = "month_" + DateTime.Now.ToString("yyMM"); break; case DirType.Ext: subFolder = "ext_" + ext; break; case DirType.Day: subFolder = "day_" + DateTime.Now.ToString("yyMMdd"); break; } fileFolder = Path.Combine(UploadConfigContext.UploadPath, folder, subFolder ); filePath = Path.Combine(fileFolder, string.Format("{0}{1}.{2}", DateTime.Now.ToString("yyyyMMddhhmmss"), new Random(DateTime.Now.Millisecond).Next(10000), ext) ); if (!Directory.Exists(fileFolder)) { Directory.CreateDirectory(fileFolder); } var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write); fs.Write(file, 0, file.Length); fs.Flush(); fs.Close(); //是图片,即使生成对应尺寸 if (ImageExt.Contains(ext)) { ThumbnailService.HandleImmediateThumbnail(filePath); } this.OnUploaded(context, filePath); } file = null; context.Response.Write(this.GetResult(localFileName, filePath, err)); context.Response.End(); }
// POST: api/Routes public IHttpActionResult Post() { string urlimg, urlkml; HttpPostedFile uploadImage = null; HttpPostedFile uploadKML = null; IEnumerable <HttpPostedFile> ffile = null; HttpFileCollection files = HttpContext.Current.Request.Files; uploadImage = files.Get("uploadImage"); uploadKML = files.Get("uploadKML"); ffile = files.GetMultiple("ffile"); int nfiles = files.Count; string strName = HttpContext.Current.Request.Form.Get("Name"); string strDescription = HttpContext.Current.Request.Form.Get("Description"); if (strName == "") { return(Content(HttpStatusCode.BadRequest, "Не указано название карты")); } if (uploadImage == null || uploadKML == null) { return(Content(HttpStatusCode.BadRequest, "Нет файла изображения маршрута или файла KML")); } // получаем имя файла из переданных параметров string fileNameImage = System.IO.Path.GetFileName(uploadImage.FileName); string fileNameKML = System.IO.Path.GetFileName(uploadKML.FileName); //формируем имя файла для сохранения в БД urlimg = String.Format("{0}_{1}{2}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), Guid.NewGuid(), Path.GetExtension(fileNameImage)); urlkml = String.Format("{0}_{1}{2}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), Guid.NewGuid(), Path.GetExtension(fileNameKML)); List <Photo> photos = new List <Photo>(); if (ffile != null) { foreach (HttpPostedFile photoFile in ffile) { string photoNameImage = System.IO.Path.GetFileName(photoFile.FileName); string urlphoto = String.Format("{0}_{1}{2}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), Guid.NewGuid(), Path.GetExtension(photoNameImage)); Photo photo = new Photo(); photo.PhotoName = urlphoto; photo.Photocreated = DateTime.Now; photo.Description = photoNameImage; photos.Add(photo); photoFile.SaveAs(HttpContext.Current.Server.MapPath("~/Contents/Files/Photo/" + urlphoto)); } } Route route = new Route(); try { route.Name = strName; route.Description = strDescription; route.RouteImage = urlimg; route.RouteKML = urlkml; db.Routes.Add(route); int saved = db.SaveChanges(); if (saved > 0) { uploadImage.SaveAs(HttpContext.Current.Server.MapPath("~/Contents/Files/Img/" + urlimg)); uploadKML.SaveAs(HttpContext.Current.Server.MapPath("~/Contents/Files/Kml/" + urlkml)); foreach (var p in photos) { p.Route = route; } } db.Photos.AddRange(photos); saved = db.SaveChanges(); if (saved < 1) { foreach (var photo in photos) { string filephoto = photo.PhotoName; try { System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/Contents/Files/Photo/" + filephoto)); } catch (Exception e) { return(Content(HttpStatusCode.BadRequest, "Ошибка удаления файла")); } } } return(Json("Маршрут успешно добавлен.")); } catch (Exception e) { return(Content(HttpStatusCode.BadRequest, "Не удалось добавить запись")); } }