0

我正在一个 ASP.net (C#) 网站上工作,该网站有一个用户输入信息的表单,它还允许用户上传图片。我正在考虑将图像路径存储在数据库(sql server 2008 r2)上并将图像保存到文件系统中。最近我们谈到了创建 WinRT 版本的可能性。我不知道 RT 开发如何管理图像的上传,涵盖两个版本的最佳方法是什么,将图像保存到文件系统或将图像直接保存到数据库?

4

1 回答 1

1

传统的MultipartFormDataPOST 可以通过 WinRT 实现。下面的代码是基于Portable Class Library (PCL)WinRT 和 .NET 的一种子集实现的,但 99% 相同。

    /// <summary>
    /// upload file
    /// </summary>
    /// <returns></returns>
    public async Task<string> UploadedFile(string filename, StreamContent streamContent)
    {
        if ((!String.IsNullOrEmpty(filename) & (streamContent != null)) != true)
        {
            throw new ArgumentException("No filename or streamContent");
        }

        // 1. File upload
        const string uploadUrl = "image/upload.ajax";

        var content = new MultipartFormDataContent { { streamContent, "file", filename } };

        var message = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            Content = content,
            RequestUri = new Uri(uploadUrl, UriKind.Relative)
        };

        var fileUploadResult = await _httpClient.SendAsync(message);

                    // Please change below response message treatment.
                    var result = await fileUploadResult.Content.ReadAsStringAsync();
        var fileUplaodJsonResult = JObject.Parse(result);
        var uploadedFileUrl = fileUplaodJsonResult["url"].Value<string>();
        Debug.WriteLine("upload: " + fileUplaodJsonResult["success"].Value<string>());

        // 2. Post image url that you posted and other messages.
        const string confirmUrl = "image/confirm.ajax";

        var confirmValue = new List<KeyValuePair<string, string>>
                              {
                                new KeyValuePair<string, string>("url", uploadedFileUrl),
// Put other messages to post


                                new KeyValuePair<string, string>("rotate", "0"), 
                             };

        var confirmResult = await _httpClient.PostAsync(confirmUrl, new FormUrlEncodedContent(confirmValue));
               // Please change below response message treatment.
        var confirmJsonResult = JObject.Parse(await confirmResult.Content.ReadAsStringAsync());
        return confirmJsonResult["url"].Value<string>();
    }

而且,您现在可以将其用作var uploadedFileUrl = await UploadedFile(fileNameOrUrl, stream);

于 2013-08-05T13:46:53.133 回答