上传和下载文件

1. 上传文件 

 FileStream fsRead = new FileStream(fileurl, FileMode.Open);
            int fsLen = (int)fsRead.Length;
            byte[] heByte = new byte[fsLen];
            fsRead.Read(heByte, 0, heByte.Length);

            long length = fsRead.Length;
            string filename = fsRead.Name.Substring(fsRead.Name.LastIndexOf("\\") + 1);
            fsRead.Close();

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http:.../cunnar/upload?cId=" + cId + "&fileId=" + contractid + "&fileLength=" + length + "&fileName=" + filename);
                request.CookieContainer = new CookieContainer();
                request.Method = "POST";
                request.ContentType = "application/octet-stream";
                request.ContentLength = heByte.Length;
                request.GetRequestStream().Write(heByte, 0, heByte.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream stream = response.GetResponseStream();
                StreamReader sr = new StreamReader(stream);
                string result = sr.ReadToEnd();

                jsonCode = Newtonsoft.Json.JsonConvert.DeserializeObject<ReturnJsonCode>(result);
            }
            catch (Exception ex)
            {
                jsonCode.code = -1;
                jsonCode.msg = "上传失败!";
            }


2. 下载文件(直接打开pdf文件的数据流)
public Stream DownloadFile(string cId, string cFileId)
    {
        ReturnJsonCode jsonCode=new ReturnJsonCode();
        try
        {
            string url = "http://.../cunnar/download?cId=" + cId +
                     "&cFileId=" + cFileId;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/pdf";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            return stream;
        }
        catch (Exception ex)
        {return null;
        }


  调用下载文件方法
        Stream fs = cert.DownloadFile("4960332", "1263932");
        MemoryStream ms = new MemoryStream();
        fs.CopyTo(ms);
        Response.ClearContent();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "inline;FileName=out.pdf");
        Response.BinaryWrite(ms.ToArray());

 

posted on 2017-06-14 13:53  阳光秋天  阅读(236)  评论(0编辑  收藏  举报