0

我正在使用 PhotoChooserTask 从 windows phone 中选择图像,然后我想将它发送file/image到服务器。

WebClient有方法UploadFileWebClientSilverlight没有这个方法。我试图使用我在这个论坛上找到的几个例子,但它不起作用。谁能从一开始就帮我做到这一点?我真的不明白Silverlight是如何工作的。

4

1 回答 1

0

您可以使用 Webclient 类上传文件为

private void UploadFile()
        {
            FileStream _data; // The file stream to be read
            string uploadUri;

            byte[] fileContent = new byte[_data.Length]; 
            int bytesRead = _data.Read(fileContent, 0, CHUNK_SIZE);

            WebClient wc = new WebClient();
            wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
            Uri u = new Uri(uploadUri);
            wc.OpenWriteAsync(u, null, new object[] { fileContent, bytesRead }); 
        }

        void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) 
        {
            if (e.Error == null)
            {
              // Upload completed without error
            }
        }

在服务器端,您可以处理

 public void ProcessRequest(HttpContext context)
    {
        if (context.Request.InputStream.Length == 0)
            throw new ArgumentException("No file input");
        if (context.Request.QueryString["fileName"] == null)
            throw new Exception("Parameter fileName not set!");

        string fileName = context.Request.QueryString["fileName"];
        string filePath = @HostingEnvironment.ApplicationPhysicalPath + "/" + fileName;
        bool appendToFile = context.Request.QueryString["append"] != null && context.Request.QueryString["append"] == "1";

        FileMode fileMode;
        if (!appendToFile)
        {
            if (File.Exists(filePath))
                File.Delete(filePath);
            fileMode = FileMode.Create;
        }
        else
        {
            fileMode = FileMode.Append;
        }
        using (FileStream fs = File.Open(filePath, fileMode))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
            fs.Close();
        }
    }

希望它会帮助你。

于 2013-04-23T14:34:28.680 回答