110,533
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// WebClient上传文件至服务器
/// </summary>
/// <param name="fileNamePath">文件名,全路径格式</param>
/// <param name="uriString">服务器文件夹路径</param>
/// <param name="IsAutoRename">是否自动按照时间重命名</param>
public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
{
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
string NewFileName = fileName;
if (IsAutoRename)
{
NewFileName = DateTime.Now.ToString("yyMMddhhmmssfff") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
}
string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (uriString.EndsWith("/") == false) uriString = uriString + "/";
uriString = uriString + NewFileName;
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
//FileStream fs = OpenFile();
BinaryReader r = new BinaryReader(fs);
try
{
////使用UploadFile方法可以用下面的格式
//myWebClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
//myWebClient.UploadFile(uriString, "PUT", fileNamePath);
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.Flush();
postStream.Close();//这句报错,远程服务器返回错误: (403) 已禁止
}
catch (Exception err)
{
throw err;
}
finally
{
fs.Dispose();
}
}
<%@ WebHandler Language="C#" Class="upload" %>
using System;
using System.Web;
public class upload : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string path;
if (context.Request.Files.Count > 0 && context.Request.Files[0].FileName != "")
{
HttpPostedFile hpf = context.Request.Files[0];
if (hpf.FileName.Contains("\\"))
path = context.Server.MapPath("../Upload/" + hpf.FileName.Substring(hpf.FileName.LastIndexOf("\\")));
else
path = context.Server.MapPath("../Upload/" + hpf.FileName);
hpf.SaveAs(path);
context.Response.Write("上传成功");
}
else
{
context.Response.Write("请选择文件");
}
}
public bool IsReusable {
get {
return false;
}
}
}