110,566
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 删除上次(不是今天)不在数据库的文件
/// </summary>
private void delLastTimeFile()
{
string p = Server.MapPath(@"\upfile");
string timeName = p + @"\ttt.t";
string last = "";
if (File.Exists(timeName))
{
last = File.ReadAllText(timeName);
if (last != "")
{
if (last != DateTime.Now.ToString("yyyyMMdd"))
{
string[] fs = Directory.GetFiles(p, last + "*");
ODB.DbHelper db = new ODB.DbHelper();
DbCommand cmd = db.GetSqlStringCommond("select count(0) from Gxh_House_MemberFile where FileNewName like @NewName");
db.AddInParameter(cmd, "NewName", DbType.String, "");
foreach (string ss in fs)
{
string s = ss.Substring(ss.LastIndexOf(@"\") + 1);
if (s.StartsWith(last))
{
db.SetParameter(cmd, "NewName", "%" + s + "%");
if ((int)db.ExecuteScalar(cmd) == 0)
{//重命名文件
File.Move(p + @"\" + s, p + @"\" + s + ".del");
}
}
}
File.WriteAllText(timeName, DateTime.Now.ToString("yyyyMMdd"));
}
}
else
File.WriteAllText(timeName, DateTime.Now.ToString("yyyyMMdd"));
}
else
{
File.WriteAllText(timeName, DateTime.Now.ToString("yyyyMMdd"));
}
}
上次没有加入这些代码,先是重命名,等下次再全用这方法再删除,也就是删除上次的旧文件<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
this.Response.ContentType = "text/html";
var files = this.Request.Files;
if (files.Count > 0)
{
var s1 = string.Format("您上传了{0}个文件,名叫 {1},一共有 {2} 字节。", files.Count, files[0].FileName, files[0].ContentLength);
this.Response.Write(s1);
this.Response.Write("<br>");
var file = this.Server.MapPath("~/app_data/" + new System.IO.FileInfo(files[0].FileName).Name);
files[0].SaveAs(file);
this.Response.Write("已经保存文件 " + file);
this.Response.End();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
</body>
</html>
上面,我增加了两句话。
然后另外一个测试小程序,你可以这样写:using System;
using System.Net;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var result= new WebClient().UploadFile("http://localhost:2171/MySite/UploadFile.aspx", "C:\\MyDocs\\test\\设计文档.doc");
Console.WriteLine(Encoding.UTF8.GetString(result));
Console.ReadKey();
}
}
}
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
var files = this.Request.Files;
if (files.Count > 0)
{
var s1 = string.Format("您上传了{0}个文件,名叫 {1},一共有 {2} 字节。", files.Count, files[0].FileName, files[0].ContentLength);
this.Response.Write(s1);
this.Response.Write("<br>");
var file = this.Server.MapPath("~/app_data/" + new System.IO.FileInfo(files[0].FileName).Name);
files[0].SaveAs(file);
this.Response.Write("已经保存文件 " + file);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
</body>
</html>
你可以试试看,你轻松随便写几行代码的aspx(或者ashx会更简练)就能完成服务了。
这个LAMP(轻量级服务器编程)年代,还在搞已经过时的沉重RPC式的WebService或者WCF,太累了!现在你只要理解http基本原理,会用json在消息中表达自定对象,这类跨平台的轻松的通讯知识来编程就好。new WebClient().UploadFile("http://localhost:2171/MySite/UploadFile.aspx", "C:\\MyDocs\\test\\设计文档.doc");
这就可以把这个doc文件上传给你的aspx(或者ashx等等)页面了。
这无需考虑什么web service之类的。无需纠结那么半天。 [WebMethod]
public string upfilebyte(byte[] b, ref string FileName)
{
try
{
MemoryStream m = new MemoryStream(b);
using (FileStream fs = File.Open(Server.MapPath(@"\upfile\" + FileName), FileMode.Create))
{
m.WriteTo(fs);
m.Close();
fs.Close();
delLastTimeFile();
return "上传成功!";
}
}
catch (Exception xx) { return xx.Message; }
}
[WebMethod]
public byte[] downfilebyte(ref string FileName)//下载
{
try
{
using (FileStream fs = File.Open(Server.MapPath(@"\upfile\" + FileName), FileMode.Open))
{
byte[] b = new byte[fs.Length];
fs.Read(b, 0, Convert.ToInt32(fs.Length));
fs.Close();
FileName = "";
return b;
}
}
catch (Exception xx) { FileName = xx.Message; return null; }
}
客户端连接service的类
using System;
using System.Collections.Generic;
using System.Text;
namespace zpgyMember.Service
{
/// <remarks/>
[System.Web.Services.WebServiceBindingAttribute(Name = "WebService_DomainSoap", Namespace = "http://zp365.com/")]
public class upfile : System.Web.Services.Protocols.SoapHttpClientProtocol
{
public upfile(string url)
{
Url = url;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="b">字节</param>
/// <param name="FileName">文件名</param>
/// <returns></returns>
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://zp365.com/upfilebyte", RequestNamespace = "http://zp365.com/", ResponseNamespace = "http://zp365.com/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string upfilebyte(byte[] b,ref string FileName)
{
try
{
object[] results = this.Invoke("upfilebyte", new object[] { b ,FileName});
FileName = (string)results[1];
return results[0].ToString();
}
catch { return null; }
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="FileName">文件名</param>
/// <returns></returns>
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://zp365.com/downfilebyte", RequestNamespace = "http://zp365.com/", ResponseNamespace = "http://zp365.com/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public byte[] downfilebyte(ref string FileName)
{
try
{
object[] results = this.Invoke("downfilebyte", new object[] {FileName });
FileName = (string)results[1];
return (byte[])results[0];
}
catch { return null; }
}
}
}
上传按键事件private void bt_Click(object sender, EventArgs e)
{
if (lb.Items.Count >= 5)
{
MessageBox.Show("最多只能上传5个附件!"); return;
}
OpenFileDialog ofd = new OpenFileDialog();
ofd.RestoreDirectory = true;
ofd.FilterIndex = 1;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (syn == null) syn = new zpgyMember.Service.upfile(Utils.upService + "/service/upfile.asmx");
using (Stream sm = ofd.OpenFile())
{
byte[] b = new byte[sm.Length];
string oldname = ofd.FileName;
oldname = oldname.Substring(oldname.LastIndexOf(@"\") + 1);
string newname = DateTime.Now.ToString("yyyyMMddHHmmss_fff") + oldname.Substring(oldname.LastIndexOf("."));
sm.Read(b, 0, Convert.ToInt32(sm.Length));
string msg = syn.upfilebyte(b, ref newname);
if (msg.StartsWith("上传成功"))
{
m.FileName += "|" + oldname;
m.FileName = m.FileName.Trim('|');
m.FileNewName += "|" + newname;
m.FileNewName = m.FileNewName.Trim('|');
bindLable(m.FileName.Split('|'), m.FileNewName.Split('|'));
} if (msg == null) msg = "网络不通";
sm.Dispose();
sm.Close();
MessageBox.Show(msg);
}
}
}
/// <summary>
/// 用户级文件保存
/// </summary>
/// <param name="p_filePath">文件保存的路径</param>
/// <param name="p_ufile">文件信息 (字节流)</param>
/// <returns>是否保存成功</returns>
private bool SaveFile(string p_filePath, byte[] p_ufile)
{
// code
FileStream p_fw = new FileStream(p_filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
p_fw.Write(p_ufile, 0, p_ufile.Length);
p_fw.Close();
}
<!-- 文件大小设定 -->
<httpRuntime maxRequestLength="1048576" executionTimeout="600"/>
</system.web>