我正在使用ownCloud(开源云),我有一个表单来上传文件
将post请求发送到处理上传的upload.php文件的表单.
请求有很多字段,需要发送所有信息和cookie.
我需要开发一个c#代码来将文件上传到云端.
在我看来,最好的方法是提出类似于表单请求的请求.
你怎么看?有什么建议?
请阅读以下解决方案但不起作用.
Sending Files using HTTP POST in c#
http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code
Upload files with HTTPWebrequest (multipart/form-data)
谢谢
这里是一些代码:
表格:
<form data-upload-id='1'
id="data-upload-form"
class="file_upload_form"
action="<?php print_unescaped(OCP\Util::linkTo('files', 'ajax/upload.php')); ?>"
method="post"
enctype="multipart/form-data"
target="file_upload_target_1">
<input type="hidden" name="MAX_FILE_SIZE" id="max_upload" value="<?php p($_['uploadMaxFilesize']) ?>">
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" id="requesttoken">
<input type="hidden" class="max_human_file_size" value="(max <?php p($_['uploadMaxHumanFilesize']); ?>)">
<input type="hidden" name="dir" value="<?php p($_['dir']) ?>" id="dir">
<input type="file" id="file_upload_start" name='files[]'/>
<a href="#" class="svg"></a>
</form>
这就是请求看到我的方式:
enter code here
Request URL:http://my-url/owncloud/index.php/apps/files/ajax/upload.php
Request Method:POST
Status Code:200 OK
Request Headersview parsed
POST /owncloud/index.php/apps/files/ajax/upload.php HTTP/1.1
Host: my-url
Connection: keep-alive
Content-Length: 730
Accept: */*
requesttoken: 0bbcd458174e76e139ad
Origin: http://my-url
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Referer: http://my-url/owncloud/index.php/apps/files
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: oc_username=tal; oc_token=f24c041e992624d10cabbaa16aa6aeea; oc_remember_login=1; __utma=220528984.2016256779.1375771228.1375771228.1375862096.2; __utmz=220528984.1375771228.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); olfsk=olfsk4827894743066281; hblid=QHgh67nWTyXfpzWe6B1Tj9Z3JM0QBCfA; 510e8a1de6274=eqavm1nikkon6ush7con3o6ar6
Request Payload
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="MAX_FILE_SIZE"
537919488
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="requesttoken"
0bbcd458174e76e139ad
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="dir"
/
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="files[]"; filename="bg.png"
Content-Type: image/png
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT--
Response Headersview parsed
HTTP/1.1 200 OK
Date: Sun, 08 Sep 2013 07:21:02 GMT
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7+squeeze16
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
X-Content-Type-Options: nosniff
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 132
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/plain; charset=utf-8
我试过这段代码
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
//StreamReader reader3 = new StreamReader(rs);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show((string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd())));
Debug.WriteLine(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch(Exception ex)
{
Debug.WriteLine("Error uploading file", ex);
if(wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
调用功能:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
nvc.Add("btn-submit-photo", "Upload");
FilesClass.HttpUploadFile("http://192.168.49.108/owncloud/index.php/apps/files/ajax/upload.php", @"C:\t.txt", "files[]", "text/plain", nvc);
来自服务器的响应是{“data”:{“message”:“身份验证错误”},“状态”:“错误”}
这意味着我被upload.php拒绝了
也许我需要发送cookie?
最佳答案 您可以使用WebDAV上传文件,而不是尝试模拟POST上传(由于安全问题,ownCloud非常困难).
只需将PUT请求发送到http://example.com/owncloud/remote.php/webdav/some/path