网站上自己写的上传方法

 


protected void btnUploadFile_ServerClick(object sender, EventArgs e)
        {
            //文件上传 方法,
            string filepath = this.txtFilePath.Value;
            filepath = filepath.Replace("/","\\");

             string serverPath = Server.MapPath("~/SaveImage"); //服务器文件夹 所在的物理目录

             string savePath = serverPath +"\\"+ filepath.Substring(filepath.LastIndexOf('\\') + 1);//
           
            MemoryStream ms = ReadFileStream(filepath);
            bool result = ThunderByHttp(ms, savePath);
            string script = "";
            if (result)
            {
                script = "alert('上传成功')";
            }
            else
            {
                script = "alert('上传失败')";
            }

            ScriptManager.RegisterStartupScript(this, this.GetType(), "", script, true);

        }

  





/// <summary> /// 将文件读入文件流中 /// </summary> /// <param name="path"></param> public MemoryStream ReadFileStream(string path) { FileStream fs = new FileStream(path, FileMode.Open); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); MemoryStream ms = new MemoryStream(data); return ms;//返回内存流 ,比如把文件,以文件流的方式写入内存中 然后从流中拿出来 //this.pictureBox1.Image =Image.FromStream(ms); } /// <summary> /// 网络上传输,以二进制写文件 /// </summary> /// <param name="input"></param> /// <param name="savepath"></param> /// <returns></returns> public static bool ThunderByHttp(Stream input, string savepath) { bool saveResult = false; BinaryReader binaryReader = new BinaryReader(input, System.Text.Encoding.ASCII); FileStream fileStream = new FileStream(savepath, FileMode.Create); BinaryWriter binaryWriter = new BinaryWriter(fileStream); try { byte[] array; while (true) { bool flag = true; array = binaryReader.ReadBytes(5120); if (flag) { if (array.Length == 0) { break; } } if (array.Length < 5120) { binaryWriter.Write(array); // Console.WriteLine("writing END the data."); saveResult = true; } binaryWriter.Write(array); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { fileStream.Close(); binaryReader.Close(); binaryWriter.Close(); } return saveResult; }

  

posted @ 2018-03-02 11:23  兴想事成  阅读(255)  评论(0编辑  收藏  举报