1 建立服務
asmx比較簡單:上傳的圖片以Base64String參數形式傳入
注意: 這個轉換是有損轉換, 將Jpeg檔案轉換成Base64String, 再轉換回來成Jpeg的檔案明顯小於原圖(我在測試時發現是這樣的.)
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Text;
namespace ChildPictureUpload
{
/// <summary>
/// Summary description for Uploadpic.
/// </summary>
[WebService(Namespace="http://xxx.xxx/ChildPictureUpload/")]
public class ChildPictureUpload : System.Web.Services.WebService
{
public ChildPictureUpload()
{
InitializeComponent();
}
#region Component Designer generated code
//Required by the Web Services Designer
private IContainer components = null;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
[WebMethod]
public bool UpLoadPictrue(string fileContent, string fileName )
{
if(fileContent.Length==0)
{
return false;
}
else
try
{
byte[] b = System.Convert.FromBase64String(fileContent);
fileName = System.Configuration.ConfigurationSettings.AppSettings["UploadFolder"] + fileName;
string path = fileName.Substring(0, fileName.LastIndexOf("//"));
System.IO.Directory.CreateDirectory(path);
System.IO.FileStream sw = new FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None, 4096, false);
sw.Write(b, 0, b.Length);
sw.Close();
return true;
}
catch
{
return false;
}
}
}
}
為便於部署,將上傳地址在web.config配置:
<add key="UploadFolder" value="c:/Inetpub/wwwroot/ChildPictures/" />
該目錄必須添加aspnet使用者相應許可權(否則如何儲存圖片檔案呢?)
2 調用服務上傳圖片
頁面部分代碼:
//save picture to remote server
ChildPictureUpload upload = new ChildPictureUpload();
Stream m = this.filePhoto.PostedFile.InputStream;
byte[] b = new byte[m.Length];
m.Seek(0, System.IO.SeekOrigin.Begin);
int i = m.Read(b,0,(int)m.Length);
string s = System.Convert.ToBase64String(b);
if( !upload.UpLoadPictrue(s,fileName) )
{
Messaging.ShowMessage(this.Page, "The picture has not been uploaded with some error.", Messaging.EmMessageType.MessageType_Error);
}
else{..}
3 webserver部署
web.config:佈建服務地址和圖片目錄
<add key="UploadServiceUrl" value="http://192.168.1.4/ChildPictureUpload/ChildPictrueUpload.asmx" />
<add key="ChildPhotoImagePath" value="ChildPhotos" />
iis網站配置中將圖片目錄和圖片伺服器的圖片存放目錄作映射
調試後通過。
實際上,上傳圖片還應該對圖片格式和大小作限制,這裡不作詳述。