c# - 如何使用 HTTP POST multipart/form-data 将文件上传到服务器?

标签 c# php post windows-phone-8 multipartform-data

我正在开发 Windows Phone 8 应用程序。我想通过 PHP Web 服务使用 MIME 类型 multipart/form-data 和一个名为“userid=SOME_ID”的字符串数据的 HTTP POST 请求上传 SQLite 数据库。

我不想使用 HttpClient、RestSharp 或 MyToolkit 等第 3 方库。我尝试了下面的代码,但它没有上传文件,也没有给我任何错误。它在 Android、PHP 等中运行良好,因此在 Web 服务中没有问题。下面是我给定的代码(用于 WP8)。有什么问题?

我已经用谷歌搜索过,但我没有具体了解 WP8

async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(DBNAME);
    //Below line gives me file with 0 bytes, why? Should I use 
    //IsolatedStorageFile instead of StorageFile
    //var file = await ApplicationData.Current.LocalFolder.GetFileAsync(DBNAME);
    byte[] fileBytes = null;
    using (var stream = await file.OpenReadAsync())
    {
        fileBytes = new byte[stream.Size];
        using (var reader = new DataReader(stream))
        {
            await reader.LoadAsync((uint)stream.Size);
            reader.ReadBytes(fileBytes);
        }
    }

    //var res = await HttpPost(Util.UPLOAD_BACKUP, fileBytes);
    HttpPost(fileBytes);
}

private void HttpPost(byte[] file_bytes)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.myserver.com/upload.php");
    httpWebRequest.ContentType = "multipart/form-data";
    httpWebRequest.Method = "POST";
    var asyncResult = httpWebRequest.BeginGetRequestStream((ar) => { GetRequestStreamCallback(ar, file_bytes); }, httpWebRequest);  
}

private void GetRequestStreamCallback(IAsyncResult asynchronousResult, byte[] postData)  
{
    //DON'T KNOW HOW TO PASS "userid=some_user_id"  
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;  
    Stream postStream = request.EndGetRequestStream(asynchronousResult);  
    postStream.Write(postData, 0, postData.Length);  
    postStream.Close();  
    var asyncResult = request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);  
}  

private void GetResponseCallback(IAsyncResult asynchronousResult)  
{  
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;  
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);  
    Stream streamResponse = response.GetResponseStream();  
    StreamReader streamRead = new StreamReader(streamResponse);  
    string responseString = streamRead.ReadToEnd();  
    streamResponse.Close();  
    streamRead.Close();  
    response.Close();  
}  

我也尝试在 Windows 8 中解决我的问题,但它也无法正常工作。

public async Task Upload(byte[] fileBytes)
{
    using (var client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture)))
        {
            content.Add(new StreamContent(new MemoryStream(fileBytes)));
            //Not sure below line is true or not
            content.Add(new StringContent("userid=farhanW8"));
            using (var message = await client.PostAsync("http://www.myserver.com/upload.php", content))
            {
                var input = await message.Content.ReadAsStringAsync();
            }
        }
    }
}

最佳答案

使用 MultipartFormDataContent 的基本实现:-

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

form.Add(new StringContent(username), "username");
form.Add(new StringContent(useremail), "email");
form.Add(new StringContent(password), "password");            
form.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "profile_pic", "hello1.jpg");
HttpResponseMessage response = await httpClient.PostAsync("PostUrl", form);

response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;

关于c# - 如何使用 HTTP POST multipart/form-data 将文件上传到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19954287/

相关文章:

c# - 如何通过代码在xps文档查看器中搜索xps文档的文本?

c# - 实际定义时为 "Namespace prefix not defined"

php - 在 Woocommerce 中结帐后更改订单总额

php - Doctrine - 关系未在数据库中创建

ruby - 有 2 次提交的 Mechanize 帖子

c# - 将模型属性表达式传递给 View

c# - 跨线程调用编译问题

php - MySQL : CONCAT_WS (' ' , name_first, name_middle, name_last) 像 '%keyword%' 有问题

python - Python 中无法解析 JSON 错误

asp.net - 对预检请求的响应未通过访问控制检查 : No 'Access-Control-Allow-Origin' header is present on the requested resource