public HttpResponseMessage Uploadfile()
        {
            object obj;
            int    iUploadedCnt = 0;
            string sPath        = "";

            try
            {
                sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/");

                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                System.Web.HttpPostedFile     hpf = hfc[0];
                if (hpf.ContentLength > 0)
                {
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        // SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
                obj = new { StatusCode = 200, data = "http://localhost:59728/Images/" + hpf.FileName };
            }
            catch (Exception ex)
            {
                obj = new { StatusCode = 500, data = new List <Book>() };
            }

            return(Request.CreateResponse(obj));


            // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
        }
Beispiel #2
0
 public ActionResult ImgUpload()
 {
     try
     {
         System.Web.HttpRequest    request    = System.Web.HttpContext.Current.Request;
         System.Web.HttpPostedFile uploadFile = request.Files[0];
         // 文件上传后的保存路径
         string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + ".jpg";//图片名称
         // img-path images路径--Start
         string filePathDate = DateTime.Now.ToShortDateString().ToString();
         filePathDate = filePathDate.Replace("-", "/");
         // img-path images路径--End
         string imagePath = "/image/" + "/" + filePathDate + "/";
         string filepath  = Server.MapPath("~/upload") + imagePath;
         if (!Directory.Exists(filepath))
         {
             Directory.CreateDirectory(filepath);
         }
         uploadFile.SaveAs(filepath + filename);
         //HttpPostedFileBase File1 = Request.Files[0];
         //检查上传的物理路径是否存在,不存在则创建
         string imgurl = HostUrl() + "/upload" + imagePath + filename;
         return(Json(new { success = true, imgurl = imgurl }));
     }
     catch (Exception ex)
     {
         return(Json(new { success = true, msg = ex.Message }));
     }
 }
Beispiel #3
0
        /// <summary>
        /// 保存文件并返回文件路径
        /// </summary>
        /// <param name="file1"></param>
        /// <returns></returns>
        public string uploadFile(System.Web.HttpPostedFile file1)
        {
            if (file1 == null)
            {
                throw new Exception("缺少上传文件!");
            }
            //判断文件类型是否正确或者用后缀
            string ext    = System.IO.Path.GetExtension(file1.FileName).ToLower();
            string suffix = ".xls,.xlsx,";

            if (suffix.ToLower().IndexOf(ext) == -1)
            {
                throw new Exception("文件格式错误!");
            }
            //获取文件存放的服务器目录
            string path = PC.Common.Config.objConfig.getStringAppSetings("tempFile");

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            //检验文件是否存在,存在则另起名保存
            string filename = System.IO.Path.GetFileName(file1.FileName);

            if (existSameFile(path, filename))
            {
                filename = System.DateTime.Now.ToString("yyMMddHHmmss") + "_" + filename;
            }
            file1.SaveAs(path + filename);
            return(path + filename);
        }
        public HttpResponseMessage Upload(int code)
        {
            int    upLoadcount = 0;
            string sPath       = System.Web.Hosting.HostingEnvironment.MapPath("/HinhAnh/");

            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                System.Web.HttpPostedFile file = files[i];
                string fileName = new FileInfo(file.FileName).Name;
                if (file.ContentLength > 0)
                {
                    if (!File.Exists(sPath + Path.GetFileName(fileName)))
                    {
                        Guid   id = Guid.NewGuid();
                        string modifiedFileName = id.ToString() + "_" + fileName;
                        if (!File.Exists(sPath + Path.GetFileName(modifiedFileName)))
                        {
                            file.SaveAs(sPath + Path.GetFileName(modifiedFileName));
                            upLoadcount++;
                            var entity = db.SanPhams.Find(code);
                            entity.HinhAnh = modifiedFileName;
                        }
                    }
                }
            }
            if (upLoadcount > 0)
            {
                db.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK, "Success"));
            }
            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error"));
        }
Beispiel #5
0
        public string UploadFiles()
        {
            int iUploadedCnt = 0;

            string sPath = "";

            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/FileTemps/");


            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;


            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
            }

            if (iUploadedCnt > 0)
            {
                return(iUploadedCnt + " Files Uploaded Successfully");
            }
            else
            {
                return("Upload Failed");
            }
        }
Beispiel #6
0
        public string UploadFiles()
        {
            int iUploadedCnt = 0;
            string path = System.Web.Hosting.HostingEnvironment.MapPath("~/uploads");

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            for(int iCnt = 0; iCnt < hfc.Count; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if(hpf.ContentLength > 0)
                {
                    string fullPath = Path.Combine(path, Path.GetFileName(hpf.FileName));
                    if (!File.Exists(fullPath))
                    {
                        hpf.SaveAs(fullPath);
                        SaveData(fullPath);
                        iUploadedCnt++;
                        continue;
                    }
                    return Path.GetFileName(hpf.FileName) + " does not exists";
                }
            }

            if(iUploadedCnt > 0)
            {
                return iUploadedCnt + " Files Uploaded Successfully";
            }
            else
            {
                return "Uploaded Failed";
            }
        }
 /// <summary>
 /// 參考用
 /// </summary>
 public void GetUploadFile()
 {
     System.Web.HttpFileCollection files  = System.Web.HttpContext.Current.Request.Files;
     System.Text.StringBuilder     strMsg = new System.Text.StringBuilder();
     for (int iFile = 0; iFile < files.Count; iFile++)
     {
         bool fileOK = false;
         System.Web.HttpPostedFile postedFile = files[iFile];
         string fileName, fileExtension;
         fileName = System.IO.Path.GetFileName(postedFile.FileName);
         if (fileName != "")
         {
             fileExtension = System.IO.Path.GetExtension(fileName);
             String[] allowedExtensions = { ".doc", ".xls", ".rar", ".zip", ".wps", ".txt", "docx", "pdf", "xls", ".jpg" };
             for (int i = 0; i < allowedExtensions.Length; i++)
             {
                 if (fileExtension == allowedExtensions[i])
                 {
                     fileOK = true;
                     break;
                 }
             }
             //if (!fileOK) Label1.Text = "不支援此類型" + fileName;
         }
         if (fileOK)
         {
             //postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("~/news/" + folder + "/attachment/") + fileName);
             //postedFile.SaveAs(Server.MapPath("upload") + "/qq.jpg");
             //if (attachment_filename == "") attachment_filename = fileName;
             //else attachment_filename = attachment_filename + "|" + fileName;
         }
     }
 }
Beispiel #8
0
        public static FileMessage UploadFile(ref System.Web.HttpPostedFile file, String filePath)
        {
            Impersonate oImpersonate    = new Impersonate();
            Boolean     wasImpersonated = Impersonate.isImpersonated();

            try
            {
                if (!wasImpersonated && oImpersonate.ImpersonateValidUser() == FileMessage.ImpersonationFailed)
                {
                    return(FileMessage.ImpersonationFailed);
                }
                else
                {
                    file.SaveAs(filePath);
                    return(FileMessage.FileCreated);
                }
            }
            catch
            {
                if (!wasImpersonated)
                {
                    oImpersonate.UndoImpersonation();
                }
                return(FileMessage.Catch);
            }
            finally
            {
                if (!wasImpersonated)
                {
                    oImpersonate.UndoImpersonation();
                }
            }
        }
Beispiel #9
0
        public SingleResponse <ArchivoModel> CargaArchivoCobertura()
        {
            SingleResponse <ArchivoModel> response = new SingleResponse <ArchivoModel>();

            try
            {
                string nombreArchivo = "";

                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                string sPath = WebConfigurationManager.AppSettings["Documentos_coberturas"];

                string filename = "";
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    System.Web.HttpPostedFile hpf = hfc[iCnt];

                    if (hpf.ContentLength > 0)
                    {
                        if (!Directory.Exists(sPath))
                        {
                            Directory.CreateDirectory(sPath);
                        }
                        if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                        {
                            hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                            nombreArchivo = Path.GetFileName(hpf.FileName);
                        }
                        else
                        {
                            StringBuilder archivoBuilder = new StringBuilder();
                            archivoBuilder.Append(sPath);
                            archivoBuilder.Append(Path.GetFileNameWithoutExtension(hpf.FileName));
                            archivoBuilder.Append("_");
                            archivoBuilder.Append(DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss"));
                            archivoBuilder.Append(Path.GetExtension(hpf.FileName));
                            filename = archivoBuilder.ToString();
                            hpf.SaveAs(filename);
                            var a = Path.GetFileNameWithoutExtension(hpf.FileName);
                            nombreArchivo = filename.Substring(filename.IndexOf(Path.GetFileNameWithoutExtension(hpf.FileName)));
                        }
                    }
                }

                response.Done(new ArchivoModel
                {
                    Ruta          = sPath + nombreArchivo,
                    NombreArchivo = nombreArchivo
                }, string.Empty);
            }
            catch (DomainException e)
            {
                response.Error(e);
            }
            catch (Exception e)
            {
                response.Error(new DomainException(Codes.ERR_00_00));
            }
            return(response);
        }
Beispiel #10
0
 public override void ReverseBind(Cell Cell)
 {
     System.Web.HttpPostedFile PostedFile = this.Request.Files[this.Collection.Table.ID + "File_" + Cell.Row.Index];
     if (PostedFile != null)
     {
         Cell.DataValue = PostedFile;
     }
 }
Beispiel #11
0
 /// <summary>
 /// Adds a <see cref="HttpFile"/> to the end of the collection.
 /// </summary>
 /// <param name="name">The name of parameter.</param>
 /// <param name="file">The posted file.</param>
 public void Add(string name, System.Web.HttpPostedFile file)
 {
     if (file == null)
     {
         throw new ArgumentNullException("file");
     }
     this.Add(new HttpFile(name, file));
 }
Beispiel #12
0
 /// <summary>
 /// Adds a <see cref="HttpRequestBody"/> to the end of the collection.
 /// </summary>
 /// <param name="file">The posted file.</param>
 public void Add(System.Web.HttpPostedFile file)
 {
     if (file == null)
     {
         throw new ArgumentNullException("file");
     }
     this.Add(new HttpRequestBody(file.InputStream));
 }
Beispiel #13
0
        public UploadFileOutput UploadWithStream()
        {
            System.Web.HttpContext context    = System.Web.HttpContext.Current;
            UploadFileOutput       returnNode = new UploadFileOutput();

            string date = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
            int    cout = context.Request.Files.Count;

            if (cout > 0)
            {
                System.Web.HttpPostedFile hpf = context.Request.Files[0];
                if (hpf != null)
                {
                    string fileExt = Path.GetExtension(hpf.FileName).ToLower();
                    //只能上传文件,过滤不可上传的文件类型

                    //string fileFilt = ".gif|.jpg|.bmp|.jpeg|.png";
                    //if (fileFilt.IndexOf(fileExt) <= -1)
                    //{
                    //    return "1";
                    //}

                    //判断文件大小
                    int length = hpf.ContentLength;
                    if (length > 16240000)
                    {
                        returnNode.error = 2;
                        returnNode.msg   = "文件大小超出限制";
                        return(returnNode);
                    }

                    if (localPath.Trim().Length == 0)
                    {
                        localPath = System.Web.HttpContext.Current.Server.MapPath("/");
                    }

                    DateTime dt               = DateTime.Now;
                    string   folderPath       = dt.Year + "\\" + dt.Month + "\\" + dt.Day + "\\";
                    string   serverFolderPath = "/" + dt.Year + "/" + dt.Month + "/" + dt.Day + "/";
                    if (Directory.Exists(localPath + folderPath) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(localPath + folderPath);
                    }

                    string fileName = System.Guid.NewGuid().ToString() + Path.GetExtension(hpf.FileName);

                    string filePath = localPath + folderPath + fileName;
                    hpf.SaveAs(filePath);
                    returnNode.error = 0;
                    returnNode.msg   = "上传成功";
                    returnNode.url   = serverPath + serverFolderPath + fileName;
                    return(returnNode);
                }
            }
            returnNode.error = 3;
            returnNode.msg   = "没有获取到文件";
            return(returnNode);
        }
Beispiel #14
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="contentType">指定contentType,会优先采用此contentType</param>
        public Attachment(System.Web.HttpPostedFile postedFile, string contentType = null)
        {
            New();//初始化属性默认值
            this.FileLength = postedFile.ContentLength;

            if (!string.IsNullOrEmpty(contentType))
            {
                this.ContentType = contentType;
            }
            else if (!string.IsNullOrEmpty(postedFile.ContentType))
            {
                this.ContentType = postedFile.ContentType;
            }
            else
            {
                this.ContentType = string.Empty;
            }

            if (!string.IsNullOrEmpty(this.ContentType))
            {
                this.ContentType = this.ContentType.Replace("pjpeg", "jpeg");
                this.MediaType   = GetMediaType(this.ContentType);
            }
            else
            {
                this.ContentType = "unknown/unknown";
                this.MediaType   = MediaType.Other;
            }

            if (Path.GetExtension(postedFile.FileName) == "")
            {
                switch (this.ContentType)
                {
                case "image/jpeg":
                    this.FileName = postedFile.FileName + ".jpg";
                    break;

                case "image/gif":
                    this.FileName = postedFile.FileName + "gif";
                    break;

                case "image/png":
                    this.FileName = postedFile.FileName + ".png";
                    break;

                default:

                    break;
                }
            }

            this.FriendlyFileName = this.FileName.Substring(this.FileName.LastIndexOf("\\") + 1);

            //自动生成用于存储的文件名称
            this.FileName = GenerateFileName(Path.GetExtension(this.FriendlyFileName));

            CheckImageInfo(postedFile.InputStream);
        }
Beispiel #15
0
        public static String UploadFile(System.Web.UI.WebControls.FileUpload UpdControl, String BaseTempPath)
        {
            BaseTempPath.Replace("/", "\\");
            if (!BaseTempPath.EndsWith("\\"))
            {
                BaseTempPath += "\\";
            }

            String FileName = System.Guid.NewGuid().ToString();

            String SourceFileName = UpdControl.PostedFile.FileName;

            int extIndex = SourceFileName.LastIndexOf(".");

            FileName += SourceFileName.Remove(0, extIndex);

            //Eventuale controllo su estensione

            if (Delete.File(FileName))
            {
                //String fullFileName = ;
                System.Web.HttpPostedFile file = UpdControl.PostedFile;

                if (!File.Exists.Directory(BaseTempPath))
                {
                    try
                    {
                        File.Create.Directory(BaseTempPath);
                    }
                    catch (Exception ex)
                    {
                    }
                }

                FileMessage result = Create.UploadFile(ref file, BaseTempPath + FileName);

                switch (result)
                {
                case FileMessage.FileCreated:
                    return(FileName);

                case FileMessage.NotDeleted:
                    return("ErrorCode.FileExist");

                case FileMessage.UploadError:
                    return("ErrorCode.UploadError");

                default:
                    return("ErrorCode.GenericError");
                }
            }
            else
            {
                return("ErrorCode.FileExist");
            }
        }
Beispiel #16
0
 public int SaveFileESX(System.Web.HttpPostedFile uploadFile, string fileName, int fileType, string fileDesc, int userId, bool overwrite)
 {
     // return value: 0 OK, -1: error, 1: file exsiting
     this._uploadbyId = userId;
     this._fileDesc   = fileDesc;
     this._mastId     = fileType;
     this.SetFilePath();
     this.SetFileNameESX(fileName);
     return(this.SaveFileESX(overwrite, uploadFile));
 }
Beispiel #17
0
        public void UploadFiles()
        {
            int iUploadedCnt = 0;

            // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
            string sPath = "";
            //sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/LC/");

            //sPath = @"D:/Upload/LC/";

            //var directory = @"D:/Upload/LC/";
            CmnDocumentPath objDocumentPath = objRequisitionService.GetUploadPath(TransactionTypeID);

            //string documentPath = objDocumentPath.PhysicalPath.ToString();
            var directory = @objDocumentPath.PhysicalPath;

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        // SAVE THE FILES IN THE FOLDER.
                        //hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        string exttension = System.IO.Path.GetExtension(hpf.FileName);
                        int    fileSerial = iCnt + 1;
                        hpf.SaveAs(directory + SPRNo + "_Doc_" + fileSerial + exttension);
                        iUploadedCnt = iUploadedCnt + 1;
                        hpf.InputStream.Dispose();
                    }
                }
            }
            SPRNo = "";

            // RETURN A MESSAGE (OPTIONAL).
            //if (iUploadedCnt > 0)
            //{
            //    return iUploadedCnt + " Files Uploaded Successfully";
            //}
            //else
            //{
            //    return "Upload Failed";
            //}
        }
Beispiel #18
0
        public ResponseViewModel UploadImage()
        {
            try
            {
                var    info  = new ResponseViewModel();
                string sPath = "~/UploadFile/WorkPhotos/";
                sPath = System.Web.Hosting.HostingEnvironment.MapPath(sPath);
                Guid guid = Guid.NewGuid();
                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                var FolderName = System.Web.HttpContext.Current.Request.Form;
                //import.Id = Convert.ToInt64(FolderName["ContactID"]);
                var PhotoPath = "";
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    System.Web.HttpPostedFile hpf = hfc[iCnt];

                    if (hpf.ContentLength > 0)
                    {
                        //var savedFilePath = (System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"UploadFile\WorkPhotos\");
                        var savedFilePath = sPath;
                        if (!Directory.Exists(savedFilePath))
                        {
                            Directory.CreateDirectory(savedFilePath);
                        }
                        var extn = Path.GetExtension(hpf.FileName);

                        //PhotoPath = sPath + "\\" + guid + ".jpg";
                        PhotoPath = sPath + "\\" + guid + extn;
                        if (!File.Exists(PhotoPath))
                        {
                            hpf.SaveAs(PhotoPath);
                            //PhotoPath = hpf.FileName;
                            PhotoPath = "/UploadFile/WorkPhotos/" + guid + extn;
                        }
                    }
                }

                responseViewModel.Content   = PhotoPath;
                responseViewModel.IsSuccess = true;
            }
            catch (Exception ex)
            {
                responseViewModel.IsSuccess = false;
                if (responseViewModel.ReturnMessage != null && responseViewModel.ReturnMessage.Count > 0)
                {
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
                else
                {
                    responseViewModel.ReturnMessage = new List <string>();
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
            }
            return(responseViewModel);
        }
Beispiel #19
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public string UploadExcel()
        {
            bool   result     = false;
            string resultPath = string.Empty;

            try
            {
                System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                for (int fileCount = 0; fileCount < files.Count; fileCount++)
                {
                    System.Web.HttpPostedFile postedfile = files[fileCount];
                    string fileExtend = System.IO.Path.GetExtension(postedfile.FileName);
                    if (fileExtend == ".xlsx" || fileExtend == ".xls" || fileExtend == ".csv")
                    {
                        string fileName = System.IO.Path.GetFileName(postedfile.FileName);
                        if (!String.IsNullOrEmpty(fileName))
                        {
                            string fileExtension = System.IO.Path.GetExtension(fileName);    //获取文件类型

                            //上传目录
                            string directory = System.Web.HttpContext.Current.Server.MapPath("/UpLoadFiles/");
                            //文件全路径
                            string path = directory + fileName;

                            //判断目录是否存在
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }
                            //文件存在就删除文件
                            if (File.Exists(path))
                            {
                                File.Delete(path);
                            }
                            //上传到服务器的路径
                            postedfile.SaveAs(path);
                            result     = true;
                            resultPath = path;
                        }
                    }
                    else
                    {
                        result     = false;
                        resultPath = "";
                    }
                }
            }
            catch (Exception)
            {
                result     = false;
                resultPath = "";
            }
            return(resultPath);
        }
Beispiel #20
0
        public SingleResponse <ArchivoTicketsModel> CargarArchivo()
        {
            SingleResponse <ArchivoTicketsModel> response = new SingleResponse <ArchivoTicketsModel>();

            try
            {
                ArchivoTicketsModel           archivoTicketsModel = new ArchivoTicketsModel();
                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                string sPath        = WebConfigurationManager.AppSettings["TICKETS_FILES_PATH"] + WebConfigurationManager.AppSettings["TICKETS_FILES_REGISTRO"];
                int    iUploadedCnt = 0;
                string filename     = "";
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    System.Web.HttpPostedFile hpf = hfc[iCnt];

                    if (hpf.ContentLength > 0)
                    {
                        if (!Directory.Exists(sPath))
                        {
                            Directory.CreateDirectory(sPath);
                        }
                        if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                        {
                            hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        }
                        else
                        {
                            StringBuilder archivoBuilder = new StringBuilder();
                            archivoBuilder.Append(sPath);
                            archivoBuilder.Append(Path.GetFileNameWithoutExtension(hpf.FileName));
                            archivoBuilder.Append("_");
                            archivoBuilder.Append(DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss"));
                            archivoBuilder.Append(Path.GetExtension(hpf.FileName));
                            filename = archivoBuilder.ToString();
                            hpf.SaveAs(filename);
                        }
                        archivoTicketsModel.NombreArchivo = hpf.FileName;
                        iUploadedCnt = iUploadedCnt + 1;
                        archivoTicketsModel.RutaArchivo = sPath;
                        response = iGestionBussiness.GuardarArchivo(archivoTicketsModel);
                    }
                }
            }
            catch (DomainException e)
            {
                response.Error(e);
            }
            catch (Exception e)
            {
                response.Error(new DomainException(Codes.ERR_00_00));
            }
            return(response);
        }
Beispiel #21
0
 private bool SaveFileESX(string fileName, System.Web.HttpPostedFile uploadFile)
 {
     try
     {
         uploadFile.SaveAs(fileName);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Beispiel #22
0
 /// <summary>
 /// 读取表单上传文件
 /// </summary>
 /// <param name="name"></param>
 /// <param name="defaultValue"></param>
 /// <returns></returns>
 public System.Web.HttpPostedFile ParamFile(string name)
 {
     System.Web.HttpPostedFile file = null;
     if (System.Web.HttpContext.Current.Request.Files[name] != null)
     {
         if (System.Web.HttpContext.Current.Request.Files[name].FileName != "")
         {
             file = System.Web.HttpContext.Current.Request.Files[name];
         }
     }
     return(file);
 }
        protected override void Page_Show()
        {
            UserInfo userinfo = GetUserInfo();

            if (userinfo == null)
            {
                ShowError("上传文件", "请登录后再上传文件,谢谢~", "", "login.aspx");
            }
            if (ispost)
            {
                int filecount = System.Web.HttpContext.Current.Request.Files.Count;
                for (int i = 0; i < filecount; i++)
                {
                    System.Web.HttpPostedFile postedfile = System.Web.HttpContext.Current.Request.Files[i];
                    if (postedfile.FileName != string.Empty)
                    {
                        string fileext      = Path.GetExtension(postedfile.FileName).ToLower();
                        string savepath     = Path.Combine("upload", DateTime.Now.ToString("yyMM"));
                        string filename     = string.Format("{0}{1}{2}", DateTime.Now.ToString("yyMMddhhmm"), Guid.NewGuid().ToString(), fileext);
                        string fullsavename = Path.Combine(savepath, filename);

                        bool     canUpload         = false;
                        string[] allowedextensions = { ".gif", ".png", ".jpeg", ".jpg", ".zip", ".rar" };
                        foreach (string allowextname in allowedextensions)
                        {
                            if (fileext == allowextname)
                            {
                                canUpload = true;
                                break;
                            }
                        }

                        if (canUpload == true)
                        {
                            YRequest.SaveRequestFile(System.Web.HttpContext.Current.Request.Files[i], Server.MapPath("~/" + fullsavename));

                            AttachmentInfo info = new AttachmentInfo();
                            info.Filename    = filename;
                            info.Filepath    = fullsavename;
                            info.Filetype    = 0;
                            info.Posterid    = userinfo.Uid;
                            info.Description = "";
                            Attachments.CreateAttachment(info);

                            string result = JavaScriptConvert.SerializeObject(info);
                            currentcontext.Response.Write(result);
                            currentcontext.Response.End();
                        }
                    }
                }
                //System.Web.HttpContext.Current.Response.Redirect("uploadfile.aspx?filename=" + uploadedfilename.Trim(','));
            }
        }
Beispiel #24
0
        /// <summary>
        /// 批量保存文件
        /// </summary>
        /// <param name="AbsoluteFilePath">文件保存路径</param>
        /// <returns>
        ///		0:上传文件成功
        ///		1:上传的文件超过指定大小
        ///		2:上传的文件格式不在指定的后缀名列表中
        ///		3:上传的文件没有后缀名
        ///		4:保存文件出错
        ///		5:没有发现上传的文件
        ///</returns>
        public int FilesNewNameSave(string AbsoluteFilePath)
        {
            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            string tmpFileExt = _UploadFileExt;

            string[] strFileExt = tmpFileExt.Split(',');
            if (files.Count < 1)
            {
                files = null;
                return(5);//没有发现上传文件;
            }
            //处理多文件
            for (int i = 0; i < files.Count; i++)
            {
                System.Web.HttpPostedFile file = files[i];
                //判断文件大小
                if (file.ContentLength > _UpFolderSize * 1024)
                {
                    return(1);
                }
                //检验后缀名,无后缀名的不做处理
                if (file.FileName != String.Empty)
                {
                    if (IsStringExists(System.IO.Path.GetExtension(file.FileName).ToLower().Trim(), strFileExt) == false)
                    {
                        return(2);
                    }
                    //保存文件
                    try
                    {
                        if (AbsoluteFilePath.LastIndexOf("\\") == AbsoluteFilePath.Length)
                        {
                            CreateDirectory(AbsoluteFilePath);
                            file.SaveAs(AbsoluteFilePath + TimeFileName(System.IO.Path.GetExtension(file.FileName)));
                        }
                        else
                        {
                            CreateDirectory(AbsoluteFilePath);
                            file.SaveAs(AbsoluteFilePath + "\\" + TimeFileName(System.IO.Path.GetExtension(file.FileName)));
                        }
                    }
                    //catch(Exception e1)
                    catch
                    {
                        //throw new Exception(e1.Source + e1.Message);
                        return(4);
                    }
                }
            }
            files = null;
            return(0);
        }
        public string UploadFiles()
        {
            int    iUploadedCnt = 0;
            string sPath        = "";

            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/UploadTemp/");
            string date = DateTime.Now.Year.ToString();

            sPath = Path.Combine(sPath, date);
            if (!Directory.Exists(sPath))
            {
                Directory.CreateDirectory(sPath);
            }
            date  = DateTime.Now.Month.ToString();
            sPath = Path.Combine(sPath, date);
            if (!Directory.Exists(sPath))
            {
                Directory.CreateDirectory(sPath);
            }
            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];
                if (hpf.ContentLength > 0)
                {
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }

                    else
                    {
                        FileInfo f = new FileInfo(sPath + Path.GetFileName(hpf.FileName));
                        f.Delete();
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
            }

            if (iUploadedCnt > 0)
            {
                return(iUploadedCnt + " Files Uploaded Successfully");
            }

            else
            {
                return("Upload Failed");
            }
        }
Beispiel #26
0
 /// <summary>
 /// 批量检验文件大小
 /// </summary>
 /// <returns></returns>
 public bool CheckFileSize()
 {
     System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
     //处理多文件
     for (int i = 0; i < files.Count; i++)
     {
         System.Web.HttpPostedFile file = files[i];
         if (file.ContentLength > _UpFolderSize * 1024)
         {
             return(false);
         }
     }
     files = null;
     return(true);
 }
Beispiel #27
0
 private bool SaveFileSplitInvoice(string fileName, System.Web.HttpPostedFile uploadFile)
 {
     try
     {
         if (uploadFile.ContentLength > 0)
         {
             uploadFile.SaveAs(fileName);
         }
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Beispiel #28
0
        /// <summary>
        /// 取得索引上传文件的文件名
        /// </summary>
        /// <param name="fileIndex">文件索引</param>
        /// <returns></returns>
        public string FileName(int fileIndex)
        {
            string fileName;

            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            if (fileIndex < 0 || fileIndex >= files.Count)
            {
                files = null;
                return("");
            }
            System.Web.HttpPostedFile file = files[fileIndex];
            fileName = System.IO.Path.GetFileName(file.FileName);
            file     = null;
            files    = null;
            return(fileName);
        }
        //[AllowAnonymous]
        public string UploadPhoto()
        {
            string sPath = System.Web.Hosting.HostingEnvironment.MapPath("/CoverPhoto/");

            System.Web.HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];

            string fileName = new FileInfo(file.FileName).Name;

            Guid id = new Guid();

            string modifiedFileName = "http://localhost:1875/CoverPhoto/" + id.ToString() + "_" + fileName;

            file.SaveAs(sPath + Path.GetFileName(modifiedFileName));

            return(modifiedFileName);
        }
Beispiel #30
0
        private int SaveFileSplitInvoice(bool overwrite, System.Web.HttpPostedFile uploadFile)
        {
            // return value: 0 OK, -1: error, 1: file exsiting
            DataAccess dba           = new DataAccess();
            string     strDBfilePath = dba.dxGetSPString("wfGetFilesRootPath");

            if (!System.IO.Directory.Exists(strDBfilePath + this._filePath))
            {
                System.IO.Directory.CreateDirectory(strDBfilePath + this._filePath);
            }
            string file = strDBfilePath + this._filePath + this._fileName;

            if (System.IO.File.Exists(file))
            {
                if (overwrite)
                {
                    if (this.SaveFileSplitInvoice(strDBfilePath + this._filePath + this._fileName, uploadFile))
                    {
                        return(0);
                    }
                    else
                    {
                        return(-1);
                    }
                }
                else
                {
                    return(1);
                }
            }

            if (this.SaveFileSplitInvoice(strDBfilePath + this._filePath + this._fileName, uploadFile))
            {
                if (this.SaveFileInfo().Equals(""))
                {
                    return(0);
                }
                else
                {
                    return(-1);
                }
            }
            else
            {
                return(-1);
            }
        }