使用byte[]进行文件上传

1.背景

   需要以byte[]数据流的方式传输文件到服务器,并在服务器还原文件。

2.代码

(1)转换为byte[]

        # region function1
            FileStream fs = File.OpenRead(@"D:\\workspace\test.txt");
            MemoryStream tempStream = new System.IO.MemoryStream();
            int bi;
            while ((bi = fs.ReadByte()) != -1)
            {
                tempStream.WriteByte(((byte)bi));
            }
            byte[] buffer = tempStream.ToArray();
            string ss = JsonConvert.SerializeObject(buffer);
            # endregion


            #region function2
            FileStream stream = new FileInfo(@"D:\\workspace\test.txt").OpenRead();
            Byte[] buffer = new Byte[stream.Length];
            //从流中读取字节块并将该数据写入给定缓冲区buffer中
            stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
            return buffer;

            #endregion

   (2)从byte[]转换为文件,并保存在给定位置

            FileStream fileStream = null;
            MemoryStream ms = new MemoryStream(buffer);
            try
            {
                string savePath = "lujing";
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                fileStream = new FileStream(savePath + fileName, FileMode.Create);
                ms.WriteTo(fileStream);
            }
            catch (Exception ex){
                throw ex;
            }
            finally
            {
                ms.Close();
                fileStream.Close();

            }

3.超过4m文件上传

   <system.web>

      <httpRuntime   maxRequestLength= "51200"   executionTimeout="3600"  targetFramework="4.5" />

    <system.web>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值