コード例 #1
0
ファイル: FileUpload.cs プロジェクト: jeason0813/fineuiofMe
 /// <summary>
 /// 将上载文件的内容保存到 Web 服务器上的指定路径
 /// </summary>
 /// <param name="filename">保存的文件的名称</param>
 public void SaveAs(string filename)
 {
     if (HasFile)
     {
         PostedFile.SaveAs(filename);
     }
 }
コード例 #2
0
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Request.Form[chkBoxName] != null)
            {
                oPostedFile = new PostedFile(AffID);
                int    fileID  = 0;
                string sError  = "";
                string sDelete = Request.Form[chkBoxName].ToString();

                //Delete from File system
                string[] sDeleteArray = sDelete.Split(',');
                for (int i = 0; i < sDeleteArray.Length; i++)
                {
                    if (sDeleteArray[i] != "")
                    {
                        fileID = Convert.ToInt32(sDeleteArray[i]);
                    }
                    string sErrorDelete = oPostedFile.DeleteFile(Page, fileID);
                    if (sErrorDelete != "")
                    {
                        sError += sErrorDelete + "<br>";
                    }
                }
                if (sError != "")
                {
                    lblInfo.Text      = "There were errors during file delete. Some files could not be deleted. See details below:<br>" + sError;
                    lblInfo.ForeColor = Color.Red;
                }
            }
            BindDataGrid();
        }
コード例 #3
0
        public override ControlResult GetResult()
        {
            HttpPostedFileBase value = this.Value;

            if (value != null)
            {
                MemoryStream memoryStream = new MemoryStream();
                value.InputStream.CopyTo(memoryStream);

                try
                {
                    var postedFile = new PostedFile(memoryStream.ToArray(), value.FileName, string.Empty);

                    var args = new FormClientUploadPipelineArgs()
                    {
                        PostedFile      = postedFile,
                        FieldParameters = this.Parameters,
                        ReturnValue     = value
                    };

                    Log.Debug("Azure File Upload: Running the formCLientUpload pipeline...", this);

                    CorePipeline.Run("formClientUpload", args);

                    return(new ControlResult(base.FieldItemId, this.Title, args.ReturnValue, this.ResultParameters, false));
                }
                catch (Exception e)
                {
                    Log.Warn("Exception during processing the form upload...", e, this);
                }
            }
            return(new ControlResult(base.FieldItemId, this.Title, null, this.ResultParameters, false));
        }
コード例 #4
0
ファイル: UploadFileContext.cs プロジェクト: zhengbo1994/TuXi
        /// <summary>
        /// 将文件保存到临时文件夹
        /// </summary>
        private void SaveFile()
        {
            //不是整个包上传
            if (!IsFullPackageUpload)
            {
                var tempDir = Path.Combine(HttpContext.Current.Server.MapPath("~"), ConfigContext.Current.DefaultConfig["upload:tempdir"], MainId, FolderName);
                if (Directory.Exists(tempDir))
                {
                    Directory.Delete(tempDir, true);
                }
                Directory.CreateDirectory(tempDir);

                if (IsRenamePostedFile)
                {
                    var newFileName = PostedFileName.Insert(PostedFileName.LastIndexOf("."), "_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    SaveFilePath = Path.Combine(tempDir, newFileName);
                }
                else
                {
                    SaveFilePath = Path.Combine(tempDir, PostedFile.FileName);
                }
                PostedFile.SaveAs(SaveFilePath);
            }
            else
            {
            }
        }
コード例 #5
0
ファイル: UploadFile.cs プロジェクト: nhatgiaoict/gencenter
 public bool SaveImageToHardDisk_Thumb()
 {
     try
     {
         if (!CheckFileExists() || !CheckExtention())
         {
             return(false);
         }
         Page   currentPage  = (Page)HttpContext.Current.Handler;
         string FullFileName = string.Empty,
         //Tên file của file upload
                fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + Path.GetExtension(PostedFile.FileName);
         string path1    = currentPage.Request.PhysicalApplicationPath.Replace("backend\\", "");
         // kiem tra xem co thu muc de chua anh upload chua;
         string        pathUploadImg = path1 + "data\\img\\";
         DirectoryInfo d             = new DirectoryInfo(pathUploadImg);
         if (d.Exists == false)
         {
             d.Create(); // chua co thi creat;
         }
         FullFileName = path1 + "data\\img\\" + fileName;
         relativeFileName_Uploaded = "data\\img\\" + fileName;
         PostedFile.SaveAs(FullFileName);
         Message = "Upload file thành công";
         fullFileName_Uploaded = FullFileName;
         CreateThumbnail(80, 80, FullFileName, ref thumbnailFullFileName);
         return(true);
     }
     catch (IOException ex)
     {
         relativeFileName_Uploaded = string.Empty;
         throw new IOException("lồi khi lưa file lên server", ex);
     }
 }
コード例 #6
0
        /// <summary>
        /// Fixed:
        /// </summary>
        private static void Save(PostedFile file, System.IO.FileInfo saveFile)
        {
            System.IO.FileStream saveFileStream = null;
            var en = Enumerable.Range(0, 100).ToArray();

            foreach (var index in en)
            {
                try
                {
                    saveFileStream = saveFile.Open(System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read);
                    if (saveFileStream != null)
                    {
                        break;
                    }
                }
                catch (System.IO.IOException)
                {
                    if (index >= en.Last())
                    {
                        throw;
                    }
                }
            }
            using (saveFileStream)
            {
                file.InputStream.CopyTo(saveFileStream);
                saveFileStream.Flush();
            }
        }
コード例 #7
0
        /// <summary>
        /// 写入内容到流中
        /// </summary>
        /// <param name="stream"></param>
        public override void WriteTo(Stream stream)
        {
            if (PostedFile.Count > 0 || ContentType == ContentType.FormData)
            {
                //写入普通区域
                foreach (var v in ProcessedData)
                {
                    if (v.Value == null)
                    {
                        continue;
                    }

                    var str = "--" + RequestBoundary + "\r\nContent-Disposition: form-data; name=\"" + v.Key + "\"\r\n\r\n";
                    stream.Write(Context.Request.Encoding.GetBytes(str));
                    if (!v.Value.IsNullOrEmpty())
                    {
                        stream.Write(Context.Request.Encoding.GetBytes(v.Value));
                    }
                    stream.Write(Context.Request.Encoding.GetBytes("\r\n"));
                }

                //写入文件
                PostedFile.ForEach(s => s.WriteTo(stream));
                var endingstr = "--" + RequestBoundary + "--";
                stream.Write(Context.Request.Encoding.GetBytes(endingstr));
            }
            else
            {
                stream.Write((ContentType == ContentType.FormUrlEncoded ? System.Text.Encoding.ASCII : Message.Encoding).GetBytes(ProcessedData.Where(s => s.Value != null).Select(s => s.Key + "=" + s.Value).Join("&")));
            }
        }
コード例 #8
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public string UploadStart()
        {
            bool   tf          = false;
            string returnvalue = "";

            if (PostedFile != null)
            {
                try
                {
                    string fileName = PathToName(PostedFile.FileName);
                    if (filename != "")
                    {
                        fileName = filename;
                    }
                    string _fileName = "";

                    string[] Exten = Extension.Split(',');
                    if (Exten.Length == 0)
                    {
                        returnvalue = "你未设置上传文件类型,系统不允许进行下一步操作!";
                    }
                    else
                    {
                        for (int i = 0; i < Exten.Length; i++)
                        {
                            if (fileName.ToLower().EndsWith(Exten[i].ToLower()))
                            {
                                if (PostedFile.ContentLength > FileLength)
                                {
                                    returnvalue = "上传文件限制大小:" + FileLength / 1024 + "kb!";
                                }
                                string IsFileex = SavePath + @"\" + fileName;
                                if (!Directory.Exists(SavePath))
                                {
                                    Directory.CreateDirectory(SavePath);
                                }
                                PostedFile.SaveAs(IsFileex);
                                _fileName   = fileName;
                                tf          = true;
                                returnvalue = "文件上传成功";
                            }
                        }
                        if (tf == false)
                        {
                            returnvalue = "只允许上传" + Extension + " 文件!";
                        }
                    }
                }
                catch (System.Exception exc)
                {
                    returnvalue = exc.Message;
                }
            }
            else
            {
                returnvalue = "上传文件失败!";
            }
            return(returnvalue);
        }
コード例 #9
0
ファイル: MyUpload.cs プロジェクト: rockcs1992/PLATE-X
    /// <summary>
    /// 文件Upload Return -1="文件I am a有问题" 0="文件超过指定大小"
    /// </summary>
    /// <returns>Return -1="文件I am a有问题" 0="文件超过指定大小"</returns>
    public string UploadRes(int userid)
    {
        string strMappath = "";

        if (this.PostedFile != null || this.PostedFile.FileName.ToString() != "")
        {
            try
            {
                string type1    = this.PostedFile.FileName.Substring(this.PostedFile.FileName.LastIndexOf(".") + 1).ToLower();
                string fileName = PathToName(PostedFile.FileName);
                if (!type(type1))
                {
                    //System.Web.HttpContext.Current.Response.Write("<script>alert('请Upload'+'"+Extension+"'+'文件');</script>");
                    //"请Upload "+Extension+" 文件!";
                    return("-1");
                }
                if (PostedFile.ContentLength > fileLength)
                {
                    //System.Web.HttpContext.Current.Response.Write("<script>alert('文件太大了!');</script>");
                    return("0");
                }
                if (this.setfilenme != "")
                {
                    strMappath = setfilenme;
                }
                else
                {
                    strMappath = Text.OrderID() + RndStr(5, true) + "." + type1;
                }

                if (!Directory.Exists(HttpContext.Current.Server.MapPath("/Resources/" + userid.ToString() + "/")))         //判断目录是否存在
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/Resources/" + userid.ToString() + "/")); //创建目录
                }

                string strym = DateTime.Now.ToString("yyyy-MM-dd");

                if (!Directory.Exists(HttpContext.Current.Server.MapPath("/Resources/" + userid.ToString() + "/" + strym + "/")))         //判断目录是否存在
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/Resources/" + userid.ToString() + "/" + strym + "/")); //创建目录
                }
                string path = this.savePath + userid.ToString() + "/" + strym + "/" + strMappath;
                PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
                return(this.SavePath + userid.ToString() + "/" + strym + "/" + strMappath);
            }
            catch
            {
            }
        }
        else
        {
            System.Web.HttpContext.Current.Response.Write("<script>alert('请选择要Upload的文件!');</script>");
            return("");
        }
        return(strMappath);
    }
コード例 #10
0
        /// <summary>
        /// 文件上传 Return -1="文件类型有问题" 0="文件超过指定大小"
        /// </summary>
        /// <returns>Return -1="文件类型有问题" 0="文件超过指定大小"</returns>
        public string UploadFile()
        {
            string strMappath = string.Empty;

            if (this.PostedFile != null || this.PostedFile.ToString() != "")
            {
                try
                {
                    string type1    = this.PostedFile.FileName.Substring(this.PostedFile.FileName.LastIndexOf(".") + 1);
                    string fileName = PathToName(PostedFile.FileName);
                    if (!string.IsNullOrEmpty(type1))
                    {
                        if (!CompareType(type1))
                        {
                            System.Web.HttpContext.Current.Response.Write("<script>alert('请上传'+'" + Extension + "'+'文件');</script>");

                            return("-1");
                        }
                        if (PostedFile.ContentLength > FileLength)
                        {
                            System.Web.HttpContext.Current.Response.Write("<script>alert('文件太大了!');</script>");
                            return("0");
                        }
                        if (!string.IsNullOrEmpty(setfilenme))
                        {
                            strMappath = this.SavePath + setfilenme + "." + type1;
                        }
                        else
                        {
                            strMappath = this.SavePath + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + type1;
                        }

                        if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(this.SavePath)))
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(this.SavePath));
                        }

                        PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(strMappath));
                        return(strMappath);
                    }
                    else
                    {
                        strMappath = "-1";
                    }
                }
                catch
                {
                    strMappath = "-1";
                }
            }
            else
            {
                return("-1");
            }
            return(strMappath);
        }
コード例 #11
0
 /// <summary>
 /// Doesn't really delete (since nothing has been persisted), but removes the object from memory and invalidates it.
 /// </summary>
 public override void DeleteImage()
 {
     PostedFile?.CleanUp();
     PostedFile    = null;
     ThumbnailFile = string.Empty;
     if (SessionKey != null && HttpContext.Current != null && HttpContext.Current.Session != null)
     {
         HttpContext.Current.Session[SessionKey] = null;
     }
 }
コード例 #12
0
        public PostedFileViewModel(ClientGuard client, PostedFile postedFile, PostedFileRoomViewModel parent)
            : base(parent, false)
        {
            this._parent = parent;

            FileId   = postedFile.File.Id;
            FileName = postedFile.File.Name;

            RemoveCommand = new Command(Remove, _ => ClientModel.Api != null);
        }
コード例 #13
0
 public FileInfo UploadDocument(PostedFile file)
 {
     try
     {
         return _fileProxyClient.UploadDocument(file);
     }
     catch (Exception ex)
     {
         ErrorSignal.FromCurrentContext().Raise(ex);
         return new FileInfo();
     }
 }
コード例 #14
0
        public virtual FileUploadResult UploadFile(string fileName)
        {
            string newName  = "";
            string fullPath = SetUniqFileName(fileName, out newName);

            PostedFile.SaveAs(fullPath);
            return(new FileUploadResult
            {
                FileName = newName,
                Status = true,
                FileSize = PostedFile.ContentLength,
            });
        }
コード例 #15
0
        public DocumentDTO GetSingleUploadedFile()
        {
            PostedFile  file = new PostedFile(Request.Files[0]);
            DocumentDTO doc  = new DocumentDTO()
            {
                ContentType    = Request.Files[0]?.ContentType,
                DocumentLength = file.ContentLength,
                DocumentName   = file.FileName,
                FileContents   = file.FileContents
            };

            return(doc);
        }
コード例 #16
0
        void BindField(string key, object value, bool enableRecursive, int level)
        {
            if (value == null)
            {
                StringField.Add(key, "");
                return;
            }

            if (value is Image)
            {
                var img = value as Image;
                PostedFile.Add(new RequestImageField(img, ImageFormat.Jpeg, 90, key, @"c:\ifish.jpg"));
                return;
            }

            var type = value.GetType();

            if (type == typeof(string) || type.IsValueType)
            {
                StringField.Add(key, value.ToString());
            }
            else if (type == typeof(byte[]))
            {
                //bytes[] 直接当作文件
                PostedFile.Add(new HttpVirtualBytePostFile(key, "", value as byte[]));
            }
            else if (type.IsSubclassOf(typeof(Stream)))
            {
                var stream = value as Stream;
                if (stream != null)
                {
                    PostedFile.Add(new HttpVirtualStreamPostFile(key, "", stream));
                }
            }
            else if (typeof(HttpPostFile).IsAssignableFrom(type))
            {
                var file = (HttpPostFile)value;
                if (string.IsNullOrEmpty(file.FieldName))
                {
                    file.FieldName = key;
                }
                PostedFile.Add(file);
            }
            else
            {
                if (enableRecursive)
                {
                    BindObject(value, key, level + 1);
                }
            }
        }
コード例 #17
0
 protected void btnUpload_Click(object sender, EventArgs e)
 {
     if (ddlHandle.SelectedValue != "Select" && ddlIndex.SelectedValue != "")
     {
         objAttachmentcls            = new AttachmentCls();
         objAttachmentcls.IndexValue = ddlIndex.SelectedValue;        // Request.QueryString["Index"];
         DataTable dt         = objAttachmentcls.GetPath();
         string    ServerPath = dt.Rows[0]["Path"].ToString() + "\\"; // "\\\\" + dt.Rows[0]["ServerName"].ToString() + "\\" + dt.Rows[0]["Path"].ToString() + "\\"; // Server.MapPath("~/Files/");//
         if (FileUpload.HasFile)
         {
             int filecount = 0;
             filecount = FileUpload.PostedFiles.Count();
             if (filecount > 0)
             {
                 foreach (HttpPostedFile PostedFile in FileUpload.PostedFiles)
                 {
                     string fileName      = Path.GetFileNameWithoutExtension(PostedFile.FileName);
                     string fileExtension = Path.GetExtension(PostedFile.FileName);
                     try
                     {
                         AttachmentCls objAttachmentcls = new AttachmentCls();
                         objAttachmentcls.AttachmentHandle = ddlHandle.SelectedValue;  // Request.QueryString["AthHandle"];
                         objAttachmentcls.IndexValue       = ddlIndex.SelectedValue;   // Request.QueryString["Index"];
                         objAttachmentcls.PurposeCode      = ddlPurpose.SelectedValue; // Request.QueryString["PurposeCode"];
                         objAttachmentcls.AttachedBy       = "0";                      //Request.QueryString["AttachedBy"];
                         objAttachmentcls.FileName         = fileName + fileExtension;
                         objAttachmentcls.LibraryCode      = dt.Rows[0]["LibCode"].ToString();
                         int nRecord = new Random(Guid.NewGuid().GetHashCode()).Next();
                         objAttachmentcls.RunningId  = nRecord;
                         objAttachmentcls.DocumentId = "AAA" + nRecord.ToString();
                         //DataTable dtDocID = objAttachmentcls.InsertAttachmentdata();
                         DataTable dtDocID = objAttachmentcls.InsertAttachmentdata();  //Change- 27-08-2018 Insert Attachment error related change
                         if (dtDocID.Rows.Count > 0)
                         {
                             PostedFile.SaveAs(ServerPath + dtDocID.Rows[0][0]);
                             ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Successfully Uploaded');", true);
                         }
                     }
                     catch (Exception ex)
                     {
                         ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('" + ex.Message + "');", true);
                     }
                 }
             }
         }
     }
     else
     {
         ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Please select all fields');", true);
     }
 }
コード例 #18
0
 public bool OverrideDocument(PostedFile file, string address)
 {
     try
     {
         DeleteFile(address);
         var Server = HttpContext.Current.Server;
         IO.File.WriteAllBytes(Server.MapPath($"~/{address}"), file.Content);
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
コード例 #19
0
 private static Attachment Attachment(string guidParam, long referenceId, PostedFile file)
 {
     return(new Attachment
     {
         Guid = guidParam,
         Name = file.FileName,
         FileName = file.FileName,
         ReferenceId = referenceId,
         Size = file.Size,
         Extention = Path.GetExtension(file.FileName),
         ContentType = file.ContentType,
         Added = true
     });
 }
コード例 #20
0
        public IEnumerable <Respondent> ReadRespondents(PostedFile file)
        {
            using (var streamReader = new StreamReader(file.InputStream))
            {
                using (var csvReader = new CsvReader(streamReader))
                {
                    csvReader.Configuration.RegisterClassMap <RespondentCsvClassMap>();

                    while (csvReader.Read())
                    {
                        yield return(csvReader.GetRecord <Respondent>());
                    }
                }
            }
        }
コード例 #21
0
        private string SaveFileToTemp(string guid, PostedFile file)
        {
            var directory = Path.Combine(DefinitionAccessor.Directories.Temp(), guid);

            Directory.CreateDirectory(directory);
            var tempFilePath = Path.Combine(directory, file.FileName);

            using (var fileStream = new FileStream(
                       tempFilePath,
                       FileMode.Create,
                       FileAccess.Write))
            {
                file.InputStream.CopyTo(fileStream);
            }
            return(tempFilePath);
        }
コード例 #22
0
ファイル: MyUpload.cs プロジェクト: rockcs1992/PLATE-X
    /// <summary>
    /// 文件Upload Return -1="文件I am a有问题" 0="文件超过指定大小"
    /// </summary>
    /// <returns>Return -1="文件I am a有问题" 0="文件超过指定大小"</returns>
    public string Upload()
    {
        string strMappath = "";

        if (this.PostedFile != null || this.PostedFile.FileName.ToString() != "")
        {
            try
            {
                string type1    = this.PostedFile.FileName.Substring(this.PostedFile.FileName.LastIndexOf(".") + 1).ToLower();
                string fileName = PathToName(PostedFile.FileName);
                if (!type(type1))
                {
                    //System.Web.HttpContext.Current.Response.Write("<script>alert('请Upload'+'"+Extension+"'+'文件');</script>");
                    //"请Upload "+Extension+" 文件!";
                    return("-1");
                }
                if (PostedFile.ContentLength > FileLength)
                {
                    //System.Web.HttpContext.Current.Response.Write("<script>alert('文件太大了!');</script>");
                    return("0");
                }
                if (this.setfilenme != "")
                {
                    strMappath = setfilenme;
                }
                else
                {
                    strMappath = Text.OrderID() + "." + type1;
                }

                PostedFile.SaveAs(this.SavePath + strMappath);
                return(strMappath);
            }
            catch
            {
            }
        }
        else
        {
            System.Web.HttpContext.Current.Response.Write("<script>alert('请选择要Upload的文件!');</script>");
            return("");
        }
        return(strMappath);
    }
コード例 #23
0
        /// <summary>
        /// 计算长度
        /// </summary>
        /// <returns></returns>
        public override long ComputeLength()
        {
            if (ContentType == ContentType.FormData)
            {
                if (string.IsNullOrEmpty(RequestBoundary))
                {
                    RequestBoundary = "ifish_network_client_" + Guid.NewGuid().ToString().Replace("-", "");
                }

                var boundary = RequestBoundary;
                WebRequset.ContentType = "multipart/form-data; boundary=" + boundary;

                var size = ProcessedData.Where(s => s.Value != null).Select(
                    s =>
                    (long)2                                                                                                                         //--
                    + boundary.Length                                                                                                               //boundary
                    + 2                                                                                                                             //\r\n
                    + 43                                                                                                                            // content-disposition
                    + s.Key.Length                                                                                                                  //key
                    + Message.Encoding.GetByteCount(s.Value)                                                                                        //value
                    + 2                                                                                                                             //\r\n
                    ).Sum();

                //attach file
                size += PostedFile.Sum(s =>
                {
                    s.AttachContext(Context);
                    return(s.ComputeLength());
                });
                size += 4 + boundary.Length;                 //结束标记
                return(size);
            }
            else
            {
                if (ContentType == ContentType.FormUrlEncoded)
                {
                    return(SerializedDataString.Length);
                }
                else
                {
                    return(Math.Max(0, ProcessedData.Select(s => s.Key.Length + 1 + (s.Value == null ? 0 : (ContentType == ContentType.FormUrlEncoded ? s.Value.Length : Message.Encoding.GetByteCount(s.Value)))).Sum() + ProcessedData.Count - 1));
                }
            }
        }
コード例 #24
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="args"></param>
 /// <returns></returns>
 private IPostedFile _PostedFileFromImage(Image image, string astype, string dispFilename)
 {
     if (image != null)
     {
         string name = "unnamed";
         if (!string.IsNullOrWhiteSpace(dispFilename))
         {
             name = dispFilename;
         }
         Action <Image, Stream> proc = null;
         string ct = null;
         if (astype == "jpeg" || astype == "jpg")
         {
             proc = ImageExtensions.SaveAsJpeg;
             ct   = "image/jpeg";
             name = name + ".jpg";
         }
         else if (astype == "gif")
         {
             proc = ImageExtensions.SaveAsGif;
             ct   = "image/gif";
             name = name + ".gif";
         }
         else if (astype == "png")
         {
             proc = ImageExtensions.SaveAsPng;
             ct   = "image/png";
             name = name + ".png";
         }
         else
         {
             throw new ArgumentException("The image type is not recognized.");
         }
         if (proc != null)
         {
             var ms = new MemoryStream();
             proc(image, ms);
             ms.Seek(0, SeekOrigin.Begin);
             var pf = new PostedFile(ct, ms.Length, name, name, m => m as Stream, ms);
             return(pf);
         }
     }
     return(null);
 }
コード例 #25
0
ファイル: MyUpload.cs プロジェクト: rockcs1992/PLATE-X
    public string Upload()
    {
        string strMappath = "";

        if (this.PostedFile != null || this.PostedFile.ToString() != "")
        {
            try
            {
                string type1    = this.PostedFile.FileName.Substring(this.PostedFile.FileName.LastIndexOf(".") + 1);
                string fileName = PathToName(PostedFile.FileName);
                if (type1 != "")
                {
                    if (!type(type1))
                    {
                        System.Web.HttpContext.Current.Response.Write("<script>alert('请Upload'+'" + Extension + "'+'文件');</script>");
                        //"请Upload "+Extension+" 文件!";
                        return("");
                    }
                    if (PostedFile.ContentLength > FileLength)
                    {
                        System.Web.HttpContext.Current.Response.Write("<script>alert('文件太大了!');</script>");
                        return("");
                    }
                    //postedFile.SaveAs(SavePath+fileName);
                    strMappath = this.savePath + System.DateTime.Now.ToFileTimeUtc() + "." + type1;
                    PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(strMappath));
                    return(strMappath);
                }
                else
                {
                    strMappath = "";
                }
            }
            catch
            {
            }
        }
        else
        {
            return("");
        }
        return(strMappath);
    }
コード例 #26
0
 public string Upload()
 {
     if (PostedFile != null)
     {
         try
         {
             string fileName = PathToName(PostedFile.FileName);
             //if (!fileName.EndsWith(Extension)) return "You must select " + Extension + " file!";
             if (PostedFile.ContentLength > FileLength)
             {
                 return("overflew");
             }
             PostedFile.SaveAs(SavePath + SaveName);
             return("success");
         }
         catch (System.Exception exc)
         { return(exc.Message); }
     }
     return("fail");
 }
コード例 #27
0
        /// <summary>
        /// Creates a PostedFile from a disk file.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="args">(string filepath, string contentType)</param>
        /// <returns></returns>
        public ParameterResolverValue PostedFile(IDataLoaderContext ctx, ParameterResolverValue[] args)
        {
            if (args.Length < 1)
            {
                throw new ArgumentException("PostedFile accepts 1 or 2 arguments (filepath[, contentType])");
            }
            var    filepath    = args[0].Value as string;
            string contentType = null;

            if (args.Length > 1)
            {
                contentType = args[1].Value as string; // TODO: Calc if missing
            }
            if (contentType == null)
            {
                if (!(new FileExtensionContentTypeProvider().TryGetContentType(filepath, out contentType)))
                {
                    contentType = "application/octet-stream";
                }
                ;
            }

            if (string.IsNullOrWhiteSpace(filepath))
            {
                throw new ArgumentException("PostedFile - filepath is empty or null");
            }
            if (!File.Exists(filepath))
            {
                throw new Exception("PostedFile - file does not exist");
            }
            var fi = new FileInfo(filepath);

            var pf = new PostedFile(contentType, fi.Length, Path.GetFileName(filepath), filepath, path =>
            {
                return(File.Open(path as string, FileMode.Open));
            }, filepath);

            return(new ParameterResolverValue(pf));
        }
コード例 #28
0
ファイル: ClientChat.cs プロジェクト: liaoyibiao1987/TCPChat
        public PostedFile GetOrCreatePostedFile(FileInfo info, string roomName)
        {
            var posted = _postedFiles.Values.FirstOrDefault(p => p.File.Name == info.Name);

            if (posted == null)
            {
                // Create new file.
                FileId id;
                while (true)
                {
                    id = new FileId(_idCreator.Next(int.MinValue, int.MaxValue), _user.Nick);
                    if (!_postedFiles.ContainsKey(id))
                    {
                        break;
                    }
                }
                var file = new FileDescription(id, info.Length, Path.GetFileName(info.Name));
                posted = new PostedFile(file, info.FullName);
                _postedFiles.Add(posted.File.Id, posted);
            }

            posted.RoomNames.Add(roomName);
            return(posted);
        }
コード例 #29
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            int     fileID            = -1;
            int     originalFileID    = -1;
            string  sKey              = "";
            string  sError            = "";
            string  sErrorVersion     = "";
            string  sErrorContentType = "";
            int     iVersion          = -1;
            bool    bRes              = false;
            string  tranName          = "";
            int     iContentType      = -1;
            int     executableCount   = 0;
            string  fileList          = "";
            DataRow oRow              = null;

            if (AffID <= 0)
            {
                return;
            }

            oPostedFile = new PostedFile(AffID);

            //1. Content type and version changes
            tranName = "updateClientApplication";
            DBase.BeginTransaction(tranName);
            DataTable oDT = DBase.GetDataTableBatch(String.Format(Config.ClientFilesBatchSQL, AffID));

            DataColumn[] PrimaryKeyArrayVersion = new DataColumn[1];
            PrimaryKeyArrayVersion[0] = oDT.Columns["ID"];
            oDT.PrimaryKey            = PrimaryKeyArrayVersion;
            for (int i = 0; i < Request.Form.AllKeys.Length; i++)
            {
                string    sFormKey = Request.Form.AllKeys[i];
                string [] tags     = sFormKey.TrimStart('_').Split('_');

                if (tags.Length < 2)
                {
                    continue;
                }

                //a. content Type
                if (tags[0] == chkComboName.TrimEnd('_'))
                {
                    fileID       = Convert.ToInt32(sFormKey.Substring(chkComboName.Length));
                    iContentType = Convert.ToInt32(Request[sFormKey]);
                    if ((fileID > 0) && (iContentType == ContentTypeExecutable))
                    {
                        executableCount++;
                    }
                    oRow = oDT.Rows.Find(fileID);
                    if ((oRow != null) && (oRow["contentTypeID"] != DBNull.Value) &&
                        (Convert.ToInt32(oRow["contentTypeID"]) != iContentType))
                    {
                        if (executableCount > 1)
                        {
                            sErrorContentType += "You can not have more than one executable file. Content type of file " + oRow["name"] + " remains the same.<br>";
                        }
                        else
                        {
                            oRow["contentTypeID"] = iContentType;
                        }
                    }
                }
                else if (tags[0] == edtName.TrimEnd('_'))                 //b. File Version
                {
                    fileID = Convert.ToInt32(tags[1]);
                    oRow   = oDT.Rows.Find(fileID);
                    if (oRow != null)
                    {
                        if (tags[2] == "version")
                        {
                            iVersion = Utils.GetInt(Request[sFormKey]);
                            if (oRow[tags[2]] != DBNull.Value)
                            {
                                if (Convert.ToInt32(oRow[tags[2]]) > iVersion)
                                {
                                    sErrorVersion += "Version you specified for file: " + oRow["name"] + " is not correct or lower than existing one. File version was not changed.<br>";
                                }
                                else if (Convert.ToInt32(oRow[tags[2]]) < iVersion)
                                {
                                    oRow[tags[2]] = iVersion;
                                }
                            }
                            else
                            {
                                oRow[tags[2]] = iVersion;
                            }
                        }
                        else
                        {
                            oRow[tags[2]] = Utils.GetInt(Request[sFormKey]);
                        }
                    }
                }
            }

            bRes = DBase.Update(oDT);
            if (bRes)
            {
                DBase.CommitTransaction(tranName);
            }
            else
            {
                DBase.RollbackTransaction(tranName);
                lblInfo.Text      = "DataBase error occured during updating table";
                lblInfo.ForeColor = Color.Red;
                return;
            }
            sError += sErrorContentType + sErrorVersion;


            //2. file upload
            for (int i = 0; i < Request.Files.Count; i++)
            {
                sKey   = Request.Files.AllKeys[i];
                fileID = -1;
                if ((sKey != null) && (sKey != ""))
                {
                    fileID = Convert.ToInt32(sKey);
                }
                originalFileID = fileID;
                iContentType   = -1;
                if (Request[chkComboName + sKey] != null)
                {
                    iContentType = Convert.ToInt32(Request[chkComboName + sKey]);
                }
                if ((iContentType == ContentTypeExecutable) && (originalFileID <= 0))
                {
                    executableCount++;
                }
                if ((executableCount > 1) && (originalFileID <= 0))
                {
                    sError += "You can not upload one more executable file. New file wasn't upload";
                }
                else
                {
                    HttpPostedFile postFile = Request.Files[i];
                    if ((postFile.FileName != "") && (postFile.FileName != null))
                    {
                        string sErrorUpload  = "";
                        string fileExtension = Path.GetExtension(postFile.FileName);
                        if (fileExtension == zipExtension)
                        {
                            sErrorUpload = oPostedFile.SaveZipFile(Page, postFile, iContentType, ref fileList);
                        }
                        else
                        {
                            sErrorUpload = oPostedFile.SaveFile(Page, postFile, iContentType, ref fileID);
                        }
                        if (sErrorUpload != "")
                        {
                            sError += sErrorUpload + "<br>";
                        }
                    }
                }
            }

            //File Upload result
            if (sError == "")
            {
                lblInfo.Text      = "File upload succeeded";
                lblInfo.ForeColor = Color.Green;
            }
            else
            {
                lblInfo.Text      = "There were errors during file upload. Some files could not be uploaded. See details below:<br>" + sError;
                lblInfo.ForeColor = Color.Red;
            }
            RunBat();
            BindDataGrid();
        }
コード例 #30
0
 public bool OverrideDocument(PostedFile file, string address)
 {
     return _fileProxyClient.OverrideDocument(file, address);
 }
コード例 #31
0
        public ActionResult Index()
        {
            var q = Request.QueryString["q"];

            if (string.IsNullOrEmpty(q))
            {
                return(View());
            }
            Uri  uri;
            bool validUrl = Uri.TryCreate(q, UriKind.Absolute, out uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);

            if (!validUrl)
            {
                return(View());
            }
            var decodedURL = HttpUtility.UrlDecode(q);

            Request.Headers.Remove("Host");
            var headers = new NameValueCollection();

            foreach (string requestHeader in Request.Headers)
            {
                headers.Add(requestHeader.ToLowerInvariant(), Request.Headers[requestHeader]);
            }

            var form = new NameValueCollection();

            foreach (string o in Request.Form)
            {
                form.Add(o, Request.Form[o]);
            }
            var files = new List <PostedFile>();

            foreach (string r in Request.Files)
            {
                var file        = new PostedFile();
                var requestFile = Request.Files[r];
                file.Name        = r;
                file.ContentType = requestFile.ContentType;
                file.FileName    = requestFile.FileName;
                using (var ms = new MemoryStream())
                {
                    requestFile.InputStream.CopyTo(ms);
                    file.Contents = ms.ToArray();
                }
                files.Add(file);
            }
            var request = new Request(new HttpMethod(Request.HttpMethod), decodedURL, headers, form)
            {
                Files = files
            };

            var _proxy = new Core.Proxy {
                AppURL = $"{Request.Url.Scheme}://{Request.Url.Authority}"
            };
            var response = _proxy.Forward(request);

            Response.StatusCode = response.HttpStatusCode.GetHashCode();
            foreach (string responseHeader in response.Headers)
            {
                Response.Headers.Set(responseHeader, response.Headers[responseHeader]);
            }

            Response.ContentType = response.Headers["content-type"];
            if (response.IsStream)
            {
                Response.OutputStream.Write(response.Bytes, 0, response.Bytes.Length);
            }
            else
            {
                Response.Output.Write(response.Content);
            }
            Response.OutputStream.Flush();


            return(null);
        }
コード例 #32
0
 public FileInfo UploadDocument(PostedFile file)
 {
     var Server = HttpContext.Current.Server;
     string address = $"DownloadFiles/FeedBack/{DateTime.Now.Year}/{DateTime.Now.Month}/";
     string absolateAddress = Server.MapPath($"~/{address}");
     bool exists = IO.Directory.Exists(absolateAddress);
     if (!exists)
         IO.Directory.CreateDirectory(absolateAddress);
     #region Upload File And Return the Url
     var path = IO.Path.Combine(absolateAddress, file.FileName);
     IO.File.WriteAllBytes(path, file.Content);
     return new FileInfo
     {
         DirectLink = $"http://Files.YekanPedia.org/{address}{file.FileName}",
         Extension = IO.Path.Combine(address, file.FileName)
     };
     #endregion
 }
コード例 #33
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <returns></returns>
 public string Upload(int _num, int isAdmin)
 {
     if (PostedFile != null)
     {
         int getFileLent = 0;
         try
         {
             //此处得到会员所在的会员组的上传信息
             if (isAdmin != 1)
             {
                 rootPublic pd = new rootPublic();
                 DataTable  dt = pd.getGroupUpInfo(NetCMS.Global.Current.UserNum);
                 if (dt != null && dt.Rows.Count > 0)
                 {
                     Extension   = dt.Rows[0]["upfileType"].ToString();
                     getFileLent = int.Parse(dt.Rows[0]["upfileSize"].ToString()) * 1024;
                 }
             }
             else
             {
                 getFileLent = FileLength;
             }
             string   fileName  = PathToName(PostedFile.FileName);
             string   _fileName = "";
             string[] Exten     = Extension.Split(',');
             if (Exten.Length == 0)
             {
                 return("你未设置上传文件类型,系统不允许进行下一步操作!$0");
             }
             else
             {
                 for (int i = 0; i < Exten.Length; i++)
                 {
                     if (fileName.ToLower().EndsWith(Exten[i].ToLower()))
                     {
                         if (PostedFile.ContentLength > getFileLent)
                         {
                             return("上传文件限制大小:" + getFileLent / 1024 + "kb!$0");
                         }
                         string IsFileex = SavePath + @"\" + fileName;
                         if (!Directory.Exists(SavePath))
                         {
                             Directory.CreateDirectory(SavePath);
                         }
                         if (_num == 1)
                         {
                             string _Randstr = NetCMS.Common.Rand.Number(6);
                             string _tmps    = DateTime.Now.Month + DateTime.Now.Day + "-" + _Randstr + "-" + fileName;
                             if (File.Exists(IsFileex))
                             {
                                 postedFile.SaveAs(SavePath + @"" + _tmps);
                                 _fileName = _tmps;
                                 return(_fileName + "$1");
                             }
                             else
                             {
                                 PostedFile.SaveAs(IsFileex);
                                 _fileName = fileName;
                                 return(_fileName + "$1");
                             }
                         }
                         else
                         {
                             PostedFile.SaveAs(IsFileex);
                             _fileName = fileName;
                             return(_fileName + "$1");
                         }
                     }
                 }
                 return("只允许上传" + Extension + " 文件!$0");
             }
         }
         catch (System.Exception exc)
         {
             return(exc.Message + "$0");
         }
     }
     else
     {
         return("上文件失败!$0");
     }
 }
コード例 #34
0
        /// <summary>
        /// 绑定对象数据
        /// </summary>
        protected void BindObject(Object obj, string prefix = "")
        {
            if (obj is IFormData)
            {
                ((IFormData)obj).GetAllFields().ForEach(s => StringField.Add(s.Key, s.Value));
            }
            else if (obj is System.Collections.Specialized.NameValueCollection)
            {
                var nvc = (System.Collections.Specialized.NameValueCollection)obj;
                nvc.AllKeys.ForEach(s => StringField.Add(s, nvc[s]));
            }
            else if (obj is Dictionary <string, string> )
            {
                var nvc = (Dictionary <string, string>)obj;
                nvc.ForEach(s => StringField.Add(s.Key, s.Value));
            }
            else if (obj is string[][])
            {
                var zigzagArray = (string[][])obj;
                foreach (var item in zigzagArray)
                {
                    StringField.Add(item[0], item[1]);
                }
            }
            else if (obj is string[, ])
            {
                var multiArray = (string[, ])obj;
                for (int i = 0; i <= multiArray.GetUpperBound(0); i++)
                {
                    StringField.Add(multiArray[i, 0], multiArray[i, 1]);
                }
            }
            else
            {
                var props = TypeDescriptor.GetProperties(obj).Cast <PropertyDescriptor>();
                foreach (var pd in props)
                {
                    if (pd.Attributes.OfType <IgnoreFieldAttribute>().Any())
                    {
                        continue;
                    }

                    var fn = pd.Attributes.OfType <FormNameAttribute>().FirstOrDefault();
                    var fp = pd.Attributes.OfType <AttachedFileAttribute>().FirstOrDefault();

                    var key = prefix + (fn == null ? pd.Name : fn.Name);
                    if (fp != null)
                    {
                        if (pd.PropertyType == typeof(string))
                        {
                            var path = (pd.GetValue(obj) ?? "").ToString();
                            if (path.IsNullOrEmpty())
                            {
                                continue;
                            }

                            PostedFile.Add(new HttpPostFile(key, path));
                        }
                        else
                        {
                            throw new InvalidOperationException("附加上传文件的属性属性只能是字符串");
                        }
                        continue;
                    }
                    var v = pd.GetValue(obj);
                    if (v == null)
                    {
                        continue;
                    }

                    //序列化
                    var satt = pd.Attributes.OfType <ObjectSerializeAttribute>().FirstOrDefault();
                    if (satt != null)
                    {
                        switch (satt.SerializeType)
                        {
                        case ObjectSerializationType.Xml:
                            StringField.Add(key, v.XmlSerializeToString());
                            break;

                        case ObjectSerializationType.Json:
                            StringField.Add(key, Newtonsoft.Json.JsonConvert.SerializeObject(v));
                            break;
                        }
                        continue;
                    }

                    if (pd.PropertyType == typeof(string) || pd.PropertyType.IsValueType)
                    {
                        StringField.Add(key, v.ToString());
                    }
                    else
                    {
                        BindObject(v, key + ".");
                    }
                }
            }
        }