码迷,mamicode.com
首页 > Web开发 > 详细

webservice跨服务器上传附件

时间:2015-03-18 12:06:15      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

最近一个项目,用到文件上传功能,本来简单地使用upload控件直接post到服务器保存,简单实现了。后来考虑到分布是部署,静态附件、图片等内容要单独服务器(命名为B服务器,一台,192.168.103.240)存储,则需要分布式服务器(命名为A服务器,可多台,测试程序就是本地 127.0.0.1)上传附件到B服务器。

考虑难易程度和易操作,简单想到的方案是:访问A服务器应用程序调用B服务器的webservice,将附件直接保存到B服务器。


 

简单实验一下,是可以达成效果的。

步骤一、B服务器的webservice代码如下:

技术分享
 1 /// <summary>
 2     /// Summary description for UploadWebService
 3     /// </summary>
 4     [WebService(Namespace = "http://tempuri.org/")]
 5     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 6     [System.ComponentModel.ToolboxItem(false)]
 7     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 8     // [System.Web.Script.Services.ScriptService]
 9     public class UploadWebService : System.Web.Services.WebService
10     {
11         [WebMethod]
12         public string HelloWorld()
13         {
14             return "Hello World";
15         }
16 
17 
18         HttpContext _context = null;
19 
20         [WebMethod]
21         public string PostFile(Byte[] content, string ext)
22         {
23             _context = this.Context;
24             string text = Convert.ToBase64String(content);
25             return Upload(ext, text);
26         }
27 
28         private string Upload(string ext, string content)
29         {
30             if (string.IsNullOrEmpty(ext) || string.IsNullOrEmpty(content))
31             {
32                 return "";
33             }
34             //保存图片
35             string dateNum = DateTime.Now.ToString("yyyyMM");//按月存放
36             string fileName = Guid.NewGuid() + ext;
37             string currentPath = HttpContext.Current.Request.PhysicalApplicationPath + "upload\\" + dateNum + "\\";
38             string fullPath = currentPath + fileName;
39 
40             if (!Directory.Exists(currentPath))
41                 Directory.CreateDirectory(currentPath);
42 
43             byte[] buffer = Convert.FromBase64String(content);
44             using (FileStream fileStream = new FileStream(fullPath, FileMode.Create))
45             {
46                 fileStream.Write(buffer, 0, buffer.Length);
47             }
48             string host = _context.Request.Url.Host;
49             int port = _context.Request.Url.Port;
50             //ResponseWrite(string.Format("http://" + host + ":" + port + "/upload/{0}/{1}", dateNum, fileName));//返回图片保存路径
51             return string.Format("http://" + host + "/" + _context.Request.ApplicationPath + "/upload/{0}/{1}", dateNum, fileName);
52         }
53 }
View Code

简单将其部署到B服务器IIS,访问验证通过,如下:

技术分享

步骤二、A服务新建web项目,A服务器的web项目,添加服务引用,增加对B服务器webservice的引用。

新建上传页面,前台页面代码如下:

技术分享
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="school.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server" action="WebForm1.aspx" method="post" enctype="multipart/form-data">
        <div>
            <input type="file" name="upload" id="upload" runat="server" />
            <input type="submit" value="upload"/>
        </div>
    </form>
</body>
</html>
View Code

后台代码如下:

技术分享
protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                var file = Request.Files["upload"];
                Stream data = file.InputStream;
                int length = (int)data.Length;
                byte[] content = new byte[length];
                data.Read(content, 0, content.Length);

                string ext = file.FileName.Substring(file.FileName.LastIndexOf(.));
                //webservice
                var client = new UploadService.UploadWebServiceSoapClient();
                string url = client.PostFile(content, ext);
                Response.Write(string.Format("<a href=\"{0}\">下载</a>", url));
            }
        }
View Code

步骤三、验证效果,如下图,输出的路径已经是B服务器的网站路径了。

技术分享

步骤四、附件大小限制

上传小附件时,没有问题,但是当上传附件很大时,就会报错:
1、没有终结点在侦听可以接受消息的
2、远程服务器返回错误: (404) 未找到
是因为没有设置上传大小的限制,超过了默认值。
在B服务器的webservice的web.config内增加如下配置:
技术分享
<configuration>
  <system.web>
    <compilation targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"  requestLengthDiskThreshold="256" maxRequestLength="2097151" />
  </system.web>
    <system.webServer>
      <security>
        <requestFiltering>
          <!--限制附件上传80MB-->
          <requestLimits maxAllowedContentLength="81920000" />
        </requestFiltering>
      </security>      
    </system.webServer>
</configuration>
View Code

重新上传附件,问题解决。


 

简单思路:分布式服务器应用程序访问同一个上传接口。

 

webservice跨服务器上传附件

标签:

原文地址:http://www.cnblogs.com/cotton/p/4346647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!