C#怎么通过WebService 上传图片

u011128440 2013-08-16 04:55:27
求大神 给写个方法看看
...全文
2328 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
candyvoice 2016-02-19
  • 打赏
  • 举报
回复
正要做一个类似的东东,学习一下
ZacharyLuke 2015-08-28
  • 打赏
  • 举报
回复
好详细啊,靠谱!
c02645 2013-08-20
  • 打赏
  • 举报
回复
引用 13 楼 u011128440 的回复:
太谢谢你了..不过我有个地方不太明白 delLastTimeFile(); 这个方法是哪里来的 需要引用什么么?
这个方法是用于删除文件的,上传就会出现旧文件,是用于删除旧文件的
 /// <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"));
            }
        }
上次没有加入这些代码,先是重命名,等下次再全用这方法再删除,也就是删除上次的旧文件
u011128440 2013-08-19
  • 打赏
  • 举报
回复
引用 3 楼 c02645 的回复:
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);
                }
            }
        }
太谢谢你了..不过我有个地方不太明白 delLastTimeFile(); 这个方法是哪里来的 需要引用什么么?
tcmakebest 2013-08-17
  • 打赏
  • 举报
回复
大家的想法基本一致,就是把图片内容转成字节数组上传,在服务器上再转回去。 其实这个方法适用于传任何文件,如果文件不太大的话,如果太大就要考虑分批上传了。
maysoft 2013-08-17
  • 打赏
  • 举报
回复
都说的很详细了
  • 打赏
  • 举报
回复
哼哼,aspx就是烂,不如ashx简洁。不过既然我给你胡乱写个aspx,就把它跑起来吧。对于这个aspx需要加入两行代码,让客户端(如果可以的话)尽量以html解析器来渲染,另外就是避免垃圾的aspx的额外内容。因此修改结果就是
<%@ 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();
        }
    }
}
  • 打赏
  • 举报
回复
我给你随便写个服务器端的服务程序吧,假设是aspx的,那么就是
<%@ 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在消息中表达自定对象,这类跨平台的轻松的通讯知识来编程就好。
  • 打赏
  • 举报
回复
引用 楼主 u011128440 的回复:
求大神 给写个方法看看
不需要自己写任何方法,因为.net框架有现成的方法。你可以写
new WebClient().UploadFile("http://localhost:2171/MySite/UploadFile.aspx", "C:\\MyDocs\\test\\设计文档.doc");
这就可以把这个doc文件上传给你的aspx(或者ashx等等)页面了。 这无需考虑什么web service之类的。无需纠结那么半天。
华为黑名单 2013-08-16
  • 打赏
  • 举报
回复
flag = service.UploadShopPictures(SourceFileCont, newfileName, type);
华为黑名单 2013-08-16
  • 打赏
  • 举报
回复
客户端 byte[] SourceFileCont = new byte[hpf.ContentLength];//设置一个字节数组用于存放图片 System.IO.Stream fs = hpf.InputStream; fs.Read(SourceFileCont, 0, hpf.ContentLength);//存入数据流中 string newfileName = CreateFileName() + hpf.FileName.Substring(hpf.FileName.Length - 4, 4); string strExt = Path.GetExtension(hpf.FileName).ToLower();
华为黑名单 2013-08-16
  • 打赏
  • 举报
回复
用字节流传输 和接收数据 public bool MakeImageByType(byte[] fs, string FileName, string categoryName , string type) { XmlDocument xml = new XmlDocument(); xml.Load(Common.GetMapPath("picture.xml")); XmlNode node = xml.SelectSingleNode(string.Format("//pictures[@category='{0}']", categoryName)); string path = Common.GetMapPath(node.Attributes["path"].Value) + DateTime.Now.Year + DateTime.Now.Month + "\\"; string _webFilePathOri = ""; // 服务器端文件路径 string _webFilePath = ""; // 服务器端缩略图路径 int upImgWidth = 0; int upImgHeight = 0; try { //判断文件夹是否存在,如果不存在,则创建一个文件夹 if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); //定义并实例化一个内存流,以存放提交上来的字节数组。 MemoryStream m = new MemoryStream(fs); //定义实际文件对象,保存上载的文件。 FileStream f = new FileStream(path + "\\" + FileName, FileMode.Create); //FileStream f = new FileStream(FileName, FileMode.Create); //把内内存里的数据写入物理文件 m.WriteTo(f); m.Close(); f.Close(); f = null; m = null; _webFilePathOri = path + FileName; // 服务器端文件路径 foreach (XmlNode pNode in node.ChildNodes) { string pPath = Common.GetMapPath(pNode.Attributes["path"].Value) + DateTime.Now.Year + DateTime.Now.Month + "\\"; upImgWidth = Convert.ToInt32(pNode.Attributes["width"].Value); upImgHeight = Convert.ToInt32(pNode.Attributes["height"].Value); if (!System.IO.Directory.Exists(pPath)) System.IO.Directory.CreateDirectory(pPath); _webFilePath = pPath + FileName;// 服务器端文件路径 MakeThumbnail(_webFilePathOri, _webFilePath, upImgWidth, upImgHeight, type);// 生成缩略图方法 } return true; } catch { return false; } } #endregion
c02645 2013-08-16
  • 打赏
  • 举报
回复
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);
                }
            }
        }
bo3235 2013-08-16
  • 打赏
  • 举报
回复
将图片 转成 byte[] 类型 增加配置的接收字符宽度就可以实现了

        /// <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>

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧