Wumaqikezi
Wumaqikezi
2020-05-13 11:04
采纳率: 100%
浏览 173

WCF 本地localhost 上传图文和文件没有问题,发布到服务器后,WCF方法能调用,但是无法实现

public static string UploadFile(string url, string path)
 {
 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
 CookieContainer cookieContainer = new CookieContainer();
 request.CookieContainer = cookieContainer;
 request.AllowAutoRedirect = true;
 request.Method = "POST";
 string boundary = DateTime.Now.Ticks.ToString("X"); 
 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
 byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
 byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
int pos = path.LastIndexOf("\\");
string fileName = path.Substring(pos + 1);
//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
//文化流  读取图片信息
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();

            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();

            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            return content;
}

图片说明 这个可以调用,但是无法实现--发布在IIS 上
图片说明 这个可以实现 --localhost 上

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • caozhy
    已采纳

    没说清楚这个upload是客户端还是服务器端,wcf是接收文件的一方还是上传的一方,哪里出错
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    这个地址是否有效

    加上日志调试下,看看具体的报错信息

    点赞 评论

相关推荐