我想实现不利用控件的文件上传
发了这个帖子:http://topic.csdn.net/u/20081113/16/2bd7bc50-9a4b-4e4b-989f-ba7fa08c8143.html
有朋友给了我这么个方法,利用webclient实现。
代码:public static bool UploadFile(string localFilePath, string serverFolder,bool reName)
{
  string fileNameExt, newFileName, uriString;
  if (reName)
  {
      fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1);
      newFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileNameExt;
  }
  else
  {
      newFileName = localFilePath.Substring(localFilePath.LastIndexOf(@"\")+1);
  } 
  if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith(@"\"))
  {
      serverFolder = serverFolder + "/";
  }  uriString = serverFolder + newFileName;   //服务器保存路径
  /**//// 创建WebClient实例
  WebClient myWebClient = new WebClient();
  myWebClient.Credentials = CredentialCache.DefaultCredentials;  // 要上传的文件
  FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.Read);
  BinaryReader r = new BinaryReader(fs);
  try
  {
      //使用UploadFile方法可以用下面的格式
      //myWebClient.UploadFile(uriString,"PUT",localFilePath);
      byte[] postArray = r.ReadBytes((int)fs.Length);
      Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
      if (postStream.CanWrite)
      {
          postStream.Write(postArray, 0, postArray.Length);
      }
      else
      {
          //MessageBox.Show("文件目前不可写!");
      }
      postStream.Close();
  }
  catch
  {
      //MessageBox.Show("文件上传失败,请稍候重试~");
      return false;
  }  return true;
}在vs中的确实现的文件的上传,也就是在本机实现了。
但是放到真正的服务器上就不行了,因为这段代码是执行在服务器的,也就是说如果我想上传c:\\tmp下的文件,代码不是在客户机上的c:\\tmp上找,而是到服务器上的相应文件夹下找,这就坏了啊!!!
本来就是想往服务器上传的,结果还要在服务器上找,这样不对啊!!!这是什么原因啊?怎么让上面上传的代码在客户端执行啊????谢谢

解决方案 »

  1.   

    这个地方你需要一个fileupload控件,然后从这个控件获取客户端文件的的文件流,webclient貌似也可以用流的方式upload吧。而不是用指定文件路径的方式来upload
      

  2.   

    WebClient类还提供了UploadFile()方法和UploadData()方法。UploadFile()方法用于把指定的文件上传到指定的位置,其中的文件名已经给出;而UploadData()方法用于把二进制数据上传至指定的URI,那些二进制数据是作为字节数组提供的(还有一个DownloadData()方法,用于从URI中检索字节数组):
    WebClient client = new WebClient();
    client.UploadFile("http://www.ourwebsite.com/NewFile.htm", 
      "C:\\WebSiteFiles\\NewFile.htm");
    byte [] image;
    // code to initialise image so it contains all the binary data for 
    // some jpg file
    client.UploadData("http://www.ourwebsite.com/NewFile.jpg", image);http://www.5ubc.net/thread-1146-1-1.html示例:只需要做适当修改
    http://industry.ccidnet.com/art/1155/20041023/797859_1.html
      

  3.   

    楼主客户端跟服务器没弄清楚要本机上传到服务器可以选择FileUpload控件
      

  4.   

    软件需要,这里不让用fileupload控件
      

  5.   

    都说了,这里不能用FileUpload控件软件需要,利用webClient不能实现吗?
      

  6.   


    这个和WEBCLIENT无关,关键是你自己获取文件路径或者是文件流的问题。
    用不用FILEUPLOAD都无所谓,用FORM表单提交也是一样的