今天在winform上需要上傳,刪除服務器上的文件,網上找了下上傳是很多,可刪除沒有找到答案,,最后只能拿個土辦法實現了,這里是用ashx文件來處理
上傳:
B/S
public void ProcessRequest(HttpContext context)
{
foreach (string fileKey in context.Request.Files)
{
try
{
HttpPostedFile file = context.Request.Files[fileKey];
string oldFileName = file.FileName; //原文件名 xxx.jpg
int extenIndex = oldFileName.LastIndexOf(".");
string getExtent = oldFileName.Substring(extenIndex);//文件擴展名 .jpg
string fileSize = UploadCommon.getFileSize(file.ContentLength); //獲取文件大小
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + (new Random()).Next(0, 9) + getExtent;
string path = "/AffixFiles/sw_Products/";
if (!Directory.Exists(context.Server.MapPath(path)))
{
Directory.CreateDirectory(context.Server.MapPath(path));
}
string filePath = Path.Combine(path, newFileName);//文件相對路徑
file.SaveAs(context.Server.MapPath(filePath));
string json = "{\"status\":\"success\",\"oldFileName\":\"" + oldFileName + "\",\"fileSize\":\"" + fileSize + "\",\"filePath\":\"" + filePath + "\",\"fileType\":\"" + getExtent + "\"}";
context.Response.Write(json);
}
catch
{
string json = "{\"status\":\"error\",\"oldFileName\":\"" + null + "\",\"fileSize\":\"" + null + "\",\"filePath\":\"" + null + "\",\"fileType\":\"" + null + "\"}";
context.Response.Write(json);
}
context.Response.End();
}
}
C/S
private void 上傳_Click(object sender, EventArgs e)
{
System.Net.WebClient myWebClient = new System.Net.WebClient();
byte[] b = myWebClient.UploadFile("http://190.160.10.13:8088/ClientUpload/ClientUploadTools.ashx",
"POST", "C:\\1351040562_Download.png");
string returnJson = Encoding.Default.GetString(b);
JavaScriptSerializer json = new JavaScriptSerializer();
uploadMessage result = json.Deserialize<uploadMessage>(returnJson);//最后的返回結果集
}
public class uploadMessage
{
public string oldFileName { get; set; }
public string fileSize { get; set; }
public string filePath { get; set; }
public string fileType { get; set; }
public string status { get; set; }
}
刪除:
這里刪除就使用了 UploadData方法來處理,太土了,大家有沒有更好的辦法提供一下哈
B/S
public void ProcessRequest(HttpContext context)
{
try
{
int totalBytes = context.Request.TotalBytes;
if (totalBytes > 0)
{
byte[] readBytes = context.Request.BinaryRead(totalBytes);
string filePath = System.Text.Encoding.Default.GetString(readBytes);
string overFile = context.Server.MapPath(filePath);
if (File.Exists(overFile))
{
try
{
File.Delete(overFile);
context.Response.Write("success");
}
catch
{
context.Response.Write("error");
}
}
}
}
catch
{
context.Response.Write("error");
}
context.Response.End();
}
C/S
/// <summary>
/// 刪除成功success 刪除失敗 error
/// </summary>
private void 刪除_Click(object sender, EventArgs e)
{
System.Net.WebClient myWebClient = new System.Net.WebClient();
byte[] b = myWebClient.UploadData(" http://localhost:2666/ClientUpload/ClientDeleteTool.ashx",
"POST", Encoding.Default.GetBytes("/AffixFiles/sw_Products/2012112211243824388.png"));
string result = Encoding.Default.GetString(b);//返回的結果
}