直接上服务契约和实现,基础找度娘、骨哥
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);
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>配置节点下