WCF REST 上传用户头像图片实例

直接上服务契约和实现,基础找度娘、骨哥

IUserService:

/// <summary>
        /// 上传用户头像
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="fileName">文件名(包含后缀)</param>
        /// <param name="fileContent">图片字节流</param>
        /// <returns></returns>
        [WebInvoke(Method = "POST", UriTemplate = "/UpHead/{userID}/{fileName}",
            ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        UserResponse UpHeadImg(String userID, String fileName, Stream fileContent);


UserService:
public UserResponse UpHeadImg(string userID, String fileName, Stream fileContent)
        {
            try
            {
                if (string.IsNullOrEmpty(userID) || string.IsNullOrEmpty(fileName)) return null;

                //获取源文件名的后缀名.{.png/.jpg}
                string extensionName = Path.GetExtension(fileName);
                if (extensionName != null) extensionName = extensionName.ToLower();

                //相对路径
                const string sitePath = "~/image/UserHead/";
                string imgFileName = userID.Trim() + extensionName; //完整图片文件名
                string siteHeadImgUrl = Path.Combine(sitePath, imgFileName); //完整头像图片文件相对路径

                //文件夹物理路径
                string path = System.Web.HttpContext.Current.Server.MapPath(sitePath);
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                //图片文件物理路径
                string imgFilePath = Path.Combine(path, imgFileName);

                //从指定的字节流创建图片对象
                Image bmp = Bitmap.FromStream(fileContent);

                //保存到物理路径
                bmp.Save(imgFilePath);

                //更新用户数据
                User user = _db.Users.Single(m => m.ID == new Guid(userID));
                user.HeadImgUrl = siteHeadImgUrl;
                if (_db.SaveChanges() > 0)
                {
                    return user.ConvertToResponse();
                }
            }
            catch (Exception)
            {
                return null;
            }
            return null;
        }

一简单Page ,一个FileUpload和提交按钮做测试:

protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                try
                {
                    Guid userID = new Guid("b4c7c71c-f0f5-4e7e-8b80-752ee9238906");
                    string name = Path.GetFileName(FileUpload1.FileName); //完整文件名(1.jpg)
                    string url = "http://localhost:14748/UserService/UpHead/" + userID + "/" + name;

                    HttpClient client = new HttpClient();
                    HttpContent content = HttpContent.Create(FileUpload1.FileContent);
                    HttpResponseMessage resp = client.Post(url, content);
                    resp.EnsureStatusIsSuccessful();

                }
                catch (WebException webException)
                {
                    throw webException;
                }
            }
        }


注意一般弹出【远程主机停止什么请求】都是这个原因:

<!--上传大文件时候必须修改以下standardEndpoint配置信息-->
<standardEndpoint   name="" maxReceivedMessageSize="3000000" defaultOutgoingResponseFormat="Json" helpEnabled="true"  automaticFormatSelectionEnabled="true">
					<readerQuotas maxArrayLength="300000"/>
				</standardEndpoint>

在 <system.serviceModel><standardEndpoints> <webHttpEndpoint>配置节点下

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值