0

我想强迫我的程序在做某事后等待片刻,然后在 asp.net 和 silverlight 中做其他事情。(具体来说,我想通过silverlight程序上传图片,然后通过Image控件在我的页面中显示。但是当我上传大小约为6KB或更大的图像时,图像不显示,但是它有已成功上传。我认为稍等片刻可能会解决问题)有人可以指导我吗?谢谢你

4

1 回答 1

0

我使用此页面中的代码

这是 MyPage.Xaml 中的代码:

 private void UploadBtn_Click(object sender, RoutedEventArgs e)
    {

        OpenFileDialog dlg = new OpenFileDialog();

        dlg.Multiselect = false;
        dlg.Filter = UPLOAD_DIALOG_FILTER;
        if ((bool)dlg.ShowDialog())
        {
            progressBar.Visibility = Visibility.Visible;
            progressBar.Value = 0;
            _fileName = dlg.File.Name;
            UploadFile(_fileName, dlg.File.OpenRead());

        }

        else
        {

            //user clicked cancel

        }

    }


    private void UploadFile(string fileName, Stream data)
    {
        // Just kept here
        progressBar.Maximum = data.Length;

        UriBuilder ub = new UriBuilder("http://mysite.com/receiver.ashx");

        ub.Query = string.Format("fileName={0}", fileName);
        WebClient c = new WebClient();

        c.OpenWriteCompleted += (sender, e) =>
        {

            PushData(data, e.Result);

            e.Result.Close();

            data.Close();

        };

        try
        {
            c.OpenWriteAsync(ub.Uri);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }

    }
    private void PushData(Stream input, Stream output)
    {
        byte[] buffer = new byte[input.Length];

        int bytesRead;
        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
        {
            output.Write(buffer, 0, buffer.Length);
        }
        progressBar.Value += input.Length;

        if (progressBar.Value >= progressBar.Maximum)
        {
            progressBar.Visibility = System.Windows.Visibility.Collapsed;
            loadImage();
        }
    }
private void loadImage()
    {
        Uri ur = new Uri("http://mysite.com/upload/" + _fileName);
        img1.Source = new BitmapImage(ur);
    }

这是receiver.ashx:

public void ProcessRequest(HttpContext context)
{
    string filename = context.Request.QueryString["filename"].ToString(); using (FileStream fs = File.Create(context.Server.MapPath("~/upload/" + filename)))
    {

        SaveFile(context.Request.InputStream, fs);

    }

}
private void SaveFile(Stream stream, FileStream fs)
{

    byte[] buffer = new byte[stream.Length];

    int bytesRead;
    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
    {

        fs.Write(buffer, 0, bytesRead);

    }

}
于 2012-05-27T08:54:08.377 回答