Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 使用HttpResponse在Silverlight中上载数据_.net_Silverlight_Httprequest_Httpresponse - Fatal编程技术网

.net 使用HttpResponse在Silverlight中上载数据

.net 使用HttpResponse在Silverlight中上载数据,.net,silverlight,httprequest,httpresponse,.net,Silverlight,Httprequest,Httpresponse,如何在Silverlight中使用异步双向二进制上传和下载数据 我需要将二进制文件上载到服务器,然后> 从服务器以二进制文件的形式获取答案 我目前使用的样本如下: 但是这个示例从一个请求开始,我需要从上传开始 我试过使用WebClient,但无法按一个顺序进行上/下操作:我所做的是由处理程序同步的。(ASHX)在Silverlight.RadFileUploader中是Telerik的组件,可与这些处理程序一起工作 namespace MyNameSpace.Web {

如何在Silverlight中使用异步双向二进制上传和下载数据

  • 我需要将二进制文件上载到服务器,然后>
  • 从服务器以二进制文件的形式获取答案
  • 我目前使用的样本如下:

    但是这个示例从一个请求开始,我需要从上传开始


    我试过使用WebClient,但无法按一个顺序进行上/下操作:

    我所做的是由处理程序同步的。(ASHX)在Silverlight.RadFileUploader中是Telerik的组件,可与这些处理程序一起工作

      namespace MyNameSpace.Web
        {   
          public class FileHandler : IHttpHandler
               {
    
          public void ProcessRequest(HttpContext context)
          {
    
            if (context.User.Identity.IsAuthenticated)
            {
    
                string fileName = context.Request.QueryString.Get("fileName");
    
                if (File.Exists(fileName))
                {                 
                    context.Response.ContentType = MimeType(fileName);
                    context.Response.AddHeader("Content-Transfer-Encoding", "binary");
                    context.Response.WriteFile(fileName, 0, length);
                }
              }
       }
    
    我删去了大部分代码,但它给出了想法。 我使用处理程序播放音频文件,使用处理程序下载音频文件。Mimetype是非常重要的部分。你的标题也很重要。这样你就可以说出你想做什么

    对于异步,本页可能会有所帮助

    编辑

    下面的处理程序文件从目录中读取一个文件
    “Top.jasper”
    ,并将其写入回调方法
    (ar.IsCompleted)
    参数的IsCompleted属性检查其是否已完成

    使用系统;
    使用System.Collections.Generic;
    使用System.Linq;
    使用System.Web;
    使用系统线程;
    使用System.IO;
    命名空间AHBSBus.Web.Classes
    {
    /// 
    ///BDT测试的摘要说明
    /// 
    公共类BDTest:IHTTPassynchandler
    {
    公共布尔可重用{get{return false;}}
    公共测试()
    {
    }
    公共IAsyncResult BeginProcessRequest(HttpContext上下文、AsyncCallback cb、Object extraData)
    {
    cb=新的异步回调((ar)=>
    {
    如果(应收账款已完成)
    {
    var result=ar.AsyncState;
    File.writealBytes(“c:\\new.jasper”,(字节[])结果);
    }
    });
    extraData=File.ReadAllBytes(“c:\\Top.jasper”);
    context.Response.Write(“开始IsThreadPoolThread是”+Thread.CurrentThread.IsThreadPoolThread+”

    \r\n”); AsynchOperation asynch=新的AsynchOperation(cb、上下文、外部数据); asynch.StartAsyncWork(); 异步返回; } 公共无效EndProcessRequest(IAsyncResult结果) { } 公共void ProcessRequest(HttpContext上下文) { var-ctx=上下文; } } 类异步操作:IAsyncResult { 私人住宅竣工; 私有对象状态; 私有异步回调\u回调; 私有HttpContext\u上下文; bool IAsyncResult.IsCompleted{get{return\u completed;} WaitHandle IAsyncResult.AsyncWaitHandle{get{return null;}} 对象IAsyncResult.AsyncState{get{return} bool IAsyncResult.CompletedSynchronously{get{return false;}} 公共异步操作(异步回调、HttpContext上下文、对象状态) { _回调=回调; _上下文=上下文; _状态=状态; _完成=错误; } 公共无效StartAsyncWork() { QueueUserWorkItem(新的WaitCallback(StartAsyncTask),null); } 私有void StartAsyncTask(对象工作项状态) { //您可以在此处修改_state对象 _context.Response.Write(“完成IsThreadPoolThread是”+Thread.CurrentThread.IsThreadPoolThread+”

    \r\n”); _Write(“来自异步处理程序的HelloWorld!”); _完成=正确; _回调(这个); } } }

    我为双向通信提供了
    signar

    AHSX是一种选择,但要特别考虑超过4 MB的文件

    您需要落实两件事:

    • 服务器端:将处理接收到的数据的Ashx HttpHandler:

      公共类文件上载:IHttpHandler { 公共void ProcessRequest(HttpContext上下文) { _httpContext=context

          if (context.Request.InputStream.Length == 0)
              throw new ArgumentException("No file input");
      
          try
          {
              // Method that will be populating parameters from HttpHandler Request.
              GetQueryStringParameters();
      
              string uploadFolder = _directory;
              string tempFileName = _fileName + _tempExtension;
      
              if (_firstChunk)
              {
                  //// Delete temp file
                  if (File.Exists(@HostingEnvironment.ApplicationPhysicalPath + "/" + uploadFolder + "/" + tempFileName))
                      File.Delete(@HostingEnvironment.ApplicationPhysicalPath + "/" + uploadFolder + "/" + tempFileName);
      
                  //// Delete target file
                  if (File.Exists(@HostingEnvironment.ApplicationPhysicalPath + "/" + uploadFolder + "/" + _fileName))
                      File.Delete(@HostingEnvironment.ApplicationPhysicalPath + "/" + uploadFolder + "/" + _fileName);
      
              }
      
      
      
              using (FileStream fs = File.Open(@HostingEnvironment.ApplicationPhysicalPath + "/" + uploadFolder + "/" + tempFileName, FileMode.Append))
              {
                  SaveFile(context.Request.InputStream, fs);
                  fs.Close();
              }
      
              if (_lastChunk)
              {
                  File.Move(HostingEnvironment.ApplicationPhysicalPath + "/" + uploadFolder + "/" + tempFileName, HostingEnvironment.ApplicationPhysicalPath + "/" + uploadFolder + "/" + _fileName);
              }
      
      
          }
          catch (Exception e)
          {
              // Todo
              // Logger Exception
              throw;
          }
      
      }
      
      }

    • 将调用它的Silverlight类:

    公共类上载文件 {

    public void上传(Stream streamNewFile,字符串文件名,字符串dirOnServer=”“) { this.uploadMode=uploadMode.OpenStream

            this.destinationOnServer = dirOnServer;
            this.fileStream = streamNewFile;
            this.fileName = fileName;
            this.dataLength = this.fileStream.Length;
    
            long dataToSend = this.dataLength - this.dataSent;
            bool isLastChunk = dataToSend <= this.chunkSize;
            bool isFirstChunk = this.dataSent == 0;
            string docType = "document";
    
            var strCurrentHost = HtmlPage.Document.DocumentUri.ToString().Substring(0, HtmlPage.Document.DocumentUri.ToString().LastIndexOf('/'));
            UriBuilder httpHandlerUrlBuilder = new UriBuilder(strCurrentHost + "/FileUpload.ashx");
            httpHandlerUrlBuilder.Query = string.Format("{5}file={0}&offset={1}&last={2}&first={3}&docType={4}&destination={6}",
                fileName, this.dataSent, isLastChunk, isFirstChunk, docType,
                string.IsNullOrEmpty(httpHandlerUrlBuilder.Query) ? string.Empty : httpHandlerUrlBuilder.Query.Remove(0, 1) + "&", destinationOnServer);
    
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(httpHandlerUrlBuilder.Uri);
            webRequest.Method = "POST";
            webRequest.BeginGetRequestStream(new AsyncCallback(this.WriteToStreamCallback), webRequest);
        }
    
    this.destinationnserver=dirOnServer;
    this.fileStream=streamNewFile;
    this.fileName=文件名;
    this.dataLength=this.fileStream.Length;
    long dataToSend=this.dataLength-this.dataSent;
    
    bool isLastChunk=dataToSend您确实意识到,同时使用两个
    WebClient
    和/或两个
    WebRequest
    对象与您玩的想法(让一个对象是双向的)是一样的吗?不,这不一样,因为我没有相同的Uri(它使用的是哈希语法)我可以使用。如果我要上传二进制文件,我不知道在其他webclient中下载到哪里,因为我没有响应对象。或者我误解了。这就是上传任何文件的方式,对吗?我在这一阶段是准确的,但我现在可以立即向silverlight客户端发送任何二进制数据。不是第二个URL和第二个请求。可以吗在服务器类说:
    fs.close()之后,您可以展开示例
    它现在应该将与演示相同的文件发送回客户机?实际上,我没有将二进制数据发送回客户机。您看过WCF Pooling Duplex吗?否则,WCF可以将流传输到目标silverlight客户机:检查这里:感谢您的回答。但它并没有解决我看到的问题。
    context.Response.WriteFile之后(文件名,0,长度);
    它会将文件写入硬盘,但不会将二进制数据发送回客户端,对吗?我需要在一个任务中接收二进制数据并回答二进制数据。它会将数据写入最终用户的浏览器而不是磁盘!
            this.destinationOnServer = dirOnServer;
            this.fileStream = streamNewFile;
            this.fileName = fileName;
            this.dataLength = this.fileStream.Length;
    
            long dataToSend = this.dataLength - this.dataSent;
            bool isLastChunk = dataToSend <= this.chunkSize;
            bool isFirstChunk = this.dataSent == 0;
            string docType = "document";
    
            var strCurrentHost = HtmlPage.Document.DocumentUri.ToString().Substring(0, HtmlPage.Document.DocumentUri.ToString().LastIndexOf('/'));
            UriBuilder httpHandlerUrlBuilder = new UriBuilder(strCurrentHost + "/FileUpload.ashx");
            httpHandlerUrlBuilder.Query = string.Format("{5}file={0}&offset={1}&last={2}&first={3}&docType={4}&destination={6}",
                fileName, this.dataSent, isLastChunk, isFirstChunk, docType,
                string.IsNullOrEmpty(httpHandlerUrlBuilder.Query) ? string.Empty : httpHandlerUrlBuilder.Query.Remove(0, 1) + "&", destinationOnServer);
    
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(httpHandlerUrlBuilder.Uri);
            webRequest.Method = "POST";
            webRequest.BeginGetRequestStream(new AsyncCallback(this.WriteToStreamCallback), webRequest);
        }