随笔-7  评论-24  文章-102  trackbacks-0

使用指定的方法将指定的本地文件上载到指定的资源

在WinForm中通过HTTP协议向服务器端上传文件


1.服务器端处理程序
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upload.aspx.cs" Inherits="Upload" %>
前台代码  Upload.aspx


using System;
using System.Web;

public partial class Upload : System.Web.UI.Page
{
    
//服务器默认保存路径
    private readonly string serverPath = @"C:\upload\";

    
private void Page_Load(object sender, System.EventArgs e)
    
{   // 获取 http提交上传的文件, 并改名保存
        foreach (string key in Request.Files.AllKeys)
        
{
            HttpPostedFile file 
= Request.Files[key];
            
string newFilename = DateTime.Now.ToString("yyMMddhhmmssffff")
                
+ file.FileName.Substring(file.FileName.LastIndexOf('.'));

            
try
            
{   //文件保存并返回相对路径地址
                file.SaveAs(this.serverPath + newFilename);
                Response.Write(
"upload/" + newFilename);
            }

            
catch (Exception)
            
{                
            }

        }

    }

}
后台代码 Upload.aspx.cs
 



2.客户端程序
       /// <summary>
        
/// 单个文件上传至服务器
        
/// </summary>
        
/// <param name="uriAddress">接收文件资源的URI, 例如: http://xxxx/Upload.aspx</param>
        
/// <param name="filePath">要发送的资源文件, 例如: @"D:\workspace\WebService 相关.doc</param>
        
/// <returns>返回文件保存的相对路径, 例如: "upload/xxxxx.jpg" 或者出错返回 ""</returns>

        private string UploadFile(string uriAddress, string filePath)
        
{
            
//利用 WebClient
            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.Credentials 
= System.Net.CredentialCache.DefaultCredentials;
            
try
            
{
                
byte[] responseArray = webClient.UploadFile(uriAddress, "POST", filePath);
                
string savePath = System.Text.Encoding.ASCII.GetString(responseArray);
                
return savePath;
            }

            
catch (Exception)
            
{
                
return "";
            }

        }



ps.判断远程文件是否存在
        public bool UriExists(string url)
        
{
            
try
            
{
                
new System.Net.WebClient().OpenRead(url);
                
return true;
            }

            
catch (System.Net.WebException)
            
{
                
return false;
            }

        }
 

posted on 2009-05-26 08:57 黄小二 阅读(5086) 评论(1)  编辑  收藏 所属分类: C#

评论:
# re: 在 WinForm中使用 WebClient上传文件 2014-11-26 17:28 | 热热
44444444444444444444444  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: