#region 上传图片
/// <summary>
/// 上传图片
/// </summary>
[WebMethod(Description = "上传图片", EnableSession = true)]
public bool UploadFile(byte[] fs, string FileName,string oldPricute)
{
try
{
///定义并实例化一个内存流,以存放提交上来的字节数组。
MemoryStream m = new MemoryStream(fs);
///定义实际文件对象,保存上载的文件。
//FileStream f = new FileStream(Server.MapPath(".") + "\\"
// + FileName, FileMode.Create);
String path = Function.GetStringValue(Application[BusParameter.PRO_IMAGE_SAVE_POSITION]);
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
FileStream f = new FileStream(path + "\\" + FileName, FileMode.Create);
///把内内存里的数据写入物理文件
m.WriteTo(f);
m.Close();
f.Close();
f = null;
m = null;
//return "文件已经上传成功。";
if (File.Exists(path + "\\" + "abc" + oldPricute + ".jpg"))
File.Delete(path + "\\" + "abc" + oldPricute + ".jpg");
return true;
}
catch (Exception ex)
{
return false;
//this.WriteErrorLog(ex);
//throw new SoapException(ex.Message, SoapException.ServerFaultCode);
}
}
#endregion
//winForm
private void button1_Click(object sender, EventArgs e) { FileInfo fi = new FileInfo(OFDialog.FileName); byte[] b = new byte[fi.Length]; System.IO.FileStream fs = fi.OpenRead(); fs.Read(b, 0, Convert.ToInt32(fi.Length)); Services.BASService.UploadFile(b, "abc" + System.Guid.NewGuid() + ".jpg",OldPricute); }
#region 下载图片 [WebMethod(Description = "Web 服务提供的方法,返回给定文件的字节数组", EnableSession = true)] public byte[] GetImage(string imgFileName) { if (String.IsNullOrEmpty(imgFileName)) { throw new ArgumentNullException("File Name Must Input"); } else { //return GetBinaryImage(Server.MapPath(imgFileName)); String path = Function.GetStringValue(Application[BusParameter.PRO_IMAGE_SAVE_POSITION]); imgFileName = path + "\\" + imgFileName; return GetBinaryImage(imgFileName); } } /// <summary> /// 返回图档的字节数组 /// </summary> /// <param name="imgFileName"></param> /// <returns></returns> private byte[] GetBinaryImage(string imgFileName) { byte[] image; if (File.Exists(imgFileName)) { try { using (FileStream fs = File.OpenRead(imgFileName)) { image = ConverStreamToByteBuffer(fs); } } catch (ArgumentNullException) { throw; } catch (InvalidCastException) { throw; } } else { image = new byte[0]; } return image; } /// <summary> /// 把给定的文件流转换为二进制字节数组 /// </summary> /// <param name="fs"></param> /// <returns></returns> private byte[] ConverStreamToByteBuffer(System.IO.Stream inStream) { int b1; using (MemoryStream ms = new MemoryStream()) { try { while ((b1 = inStream.ReadByte()) != -1) { ms.WriteByte((byte)b1); } } catch (System.InvalidCastException) { throw; } return ms.ToArray(); } } #endregion
//winForm
byte[] proImage = Services.BASService.GetImage(string.Format("abc{0}.jpg",this.Pricture)); picProduct.Image = Converter.BytesToBitmap(proImage);//picProduct为pictureBox控件
本文转自:http://www.cnblogs.com/xvqm00/archive/2009/09/09/1563412.html