Web Service服务 :在客户端将图片保存至图片服务器

来源:互联网 发布:广州大数据行业协会 编辑:程序博客网 时间:2024/05/16 13:01

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站点配置中将图片目录和图片服务器的图片存放目录作映射

调试后通过。

实际上,上传图片还应该对图片格式和大小作限制,这里不作详述。

 

原创粉丝点击