[英]Uploading file using Httpwebrequest
我想將文件上傳到服務器。 我寫了這個函數來將文件上傳到localhost服務器(我使用的是wamp服務器):
private void button1_Click_1(object sender, EventArgs e)
{
FileStream fstream = new FileStream(@"C:\Users\Albert\Documents\10050409_3276.doc", FileMode.OpenOrCreate);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/upload_file");
request.Method = "PUT";
request.ContentLength = fstream.Length;
request.AllowWriteStreamBuffering = true;
Stream request_stream = request.GetRequestStream();
byte[] indata = new byte[1024];
int bytes_read = fstream.Read(indata, 0, indata.Length);
while (bytes_read > 0)
{
request_stream.Write(indata, 0, indata.Length);
bytes_read = fstream.Read(indata, 0, indata.Length);
}
fstream.Close();
request_stream.Close();
request.GetResponse();
MessageBox.Show("ok");
}
因此,當我點擊按鈕時,異常apper說:
附加信息:遠程服務器返回錯誤:(405)方法不允許。
我嘗試使用“POST”而不是“PUT”,所以程序工作,消息框似乎說'ok',但是當我打開localhost-> upload_file(文件夾)時,我找不到任何文件。
我用wamp server測試了我的程序=>發生了問題。
我用真實服務器測試了我的程序並輸入了網絡憑據,並嘗試上傳到具有(777)權限=>發生問題的文件夾。
那問題究竟在哪里?
謝謝 :)
嘗試使用webClient
WebClient client = new WebClient();
byte[] bret = client.UploadFile(path, "POST", FilePath);
//path==URL
//FilePath==Your uploading file path
要么
WebClient webClient = new WebClient();
string webAddress = null;
try
{
webAddress = @"http://localhost/upload_file/";
webClient.Credentials = CredentialCache.DefaultCredentials;
WebRequest serverRequest = WebRequest.Create(webAddress);
serverRequest.Credentials = CredentialCache.DefaultCredentials;
WebResponse serverResponse;
serverResponse = serverRequest.GetResponse();
serverResponse.Close();
webClient.UploadFile(path, "POST", FilePath);
webClient.Dispose();
webClient = null;
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
(代碼或部分我沒試過)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.