将文件async上传到ApiController的方法

时间:2014-01-11 21:50:03

标签: asp.net-mvc asp.net-web-api

我有以下ApiController(服务器)上传文件的方法:

public class UploadController : ApiController
{    
    public Task<IEnumerable<FileDesc>> Post()
    {
        string folderName = "UploadFiles";
        string PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
        string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);


        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);

            var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
            {

                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }

                var fileInfo = streamProvider.FileData.Select(i =>
                {
                    var info = new FileInfo(i.LocalFileName);
                    return new FileDesc(info.Name, PATH + "/" + info.Name, info.Length / 1024);
                });
                return fileInfo;
            });

            return task;
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }

    }

和以下代码调用此方法(客户端):

    private void UploadFiles(string file)
    {
        ThreadSafeUpdateStatus(Properties.Resources.Sending1);
        ProgressMessageHandler progress = new ProgressMessageHandler();
        progress.HttpSendProgress += new EventHandler<HttpProgressEventArgs>(HttpSendProgress);

        HttpRequestMessage message = new HttpRequestMessage();
        MultipartFormDataContent content = new MultipartFormDataContent();

        if (!System.IO.File.Exists(file))
        {
            Error("Upload files", "File '" + file + "' not found", "Screenshot was not published. Please, try again.", true);
        }
        FileStream filestream = new FileStream(file, FileMode.Open);

        content.Add(new StreamContent(filestream), "file", _filename);

        message.Method = HttpMethod.Post;
        message.Content = content;
        message.RequestUri = new Uri(((App)Application.Current).HostRESTful);

        try
        {
            var client = HttpClientFactory.Create(progress);
            sending = client.SendAsync(message);
            CancellationToken token = cts.Token;

            string error = Properties.Resources._SendingFailedUnknownError;
            sending.ContinueWith(task =>
            {
                try
                {
                    bool resultUpload = ServiceTools.HttpResult(task, "SendingWindow/UploadFiles : upload file to server"); // если false - Окно с линками всё-равно открыто!!!!

                    if (resultUpload)
                    {
                        var ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                        string lang = String.Empty;
                        Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
                        {
                            lang = Thread.CurrentThread.CurrentCulture.ToString();
                        });

                        var clientDescr = new HttpClient();

                        var postData = new List<KeyValuePair<string, string>>();
                        postData.Add(new KeyValuePair<string, string>("filename", _filename));
                        postData.Add(new KeyValuePair<string, string>("clientDateTime", DateTime.Now.ToString("yyyy.dd.MM HH:mm")));
                        postData.Add(new KeyValuePair<string, string>("title", _title));
                        postData.Add(new KeyValuePair<string, string>("description", _description));
                        postData.Add(new KeyValuePair<string, string>("isPublic", _isPublic.ToString()));
                        postData.Add(new KeyValuePair<string, string>("version", ver.Major.ToString() + "." + ver.Minor.ToString() + "." + ver.Build.ToString()));
                        postData.Add(new KeyValuePair<string, string>("lang", lang));

                        HttpContent contentDescr = new FormUrlEncodedContent(postData);

                        clientDescr.PutAsync(((App)Application.Current).HostRESTful, contentDescr).ContinueWith(

                        ThreadSafeUpdateStatus(Properties.Resources._SendingSuccess);
                        ShellFolder.UpdateElementScreenshotsXmlAsSent(System.IO.Path.GetFileName(file));

                        Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
                        {
                            Close();
                        });


                    }
                    else
                    {

                    }
                }
                catch (Exception ex)
                {
                    error = Properties.Resources._RemoteServerNotAvailable;

                    TryToSendAgain(error);
                }
            }, token);
        }
        catch (Exception ex)
        {
            ServiceTools.WriteToWebService("SendingWindow/UploadFiles: publishing", ex);
            MessageBox.Show("Unknown error during publishing");

            Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
            {
                Close();
                //FadeClosing();
            });
        }
    }

它工作正常,但只有当PC安装了.NET 4.5时!如果PC没有它 - 我收到“发布时出现未知错误”错误和异常

  

无法加载类型'System.Net.Http.Handlers.ProgressMessageHandler'   来自程序集'System.Net.Http.Formatting,Version = 4.0.0.0,   Culture = neutral,PublicKeyToken = 31bf3856ad364e35'

我花了2天时间来解决它 - 没有结果。解决方案可以编译,但无法加载类型!我需要在装有.NET 4.0(并且没有.NET 4.5)的PC上启动我的应用程序,因此我解决了重写客户端部分以使用HttpWebRequest / HttpWebResponse(或WebClient)。但我真的不明白如何使用HttpWebRequest / HttpWebResponse正确调用“ht_tp://my...domain/api/upload”。或者我甚至同意重写服务器部分,但不知道如何通过进步来完成它。 或者我很高兴,如果有人告诉我如何解决.NET 4.5要求的这个愚蠢问题。我已经阅读了关于stackoverflow的所有帖子 - 没有帮助我...

0 个答案:

没有答案