gpt4 book ai didi

c# - 如何使用 POST 在 HTTP 服务器上上传文件?

转载 作者:可可西里 更新时间:2023-11-01 16:30:57 24 4
gpt4 key购买 nike

我正在尝试使用 POST 在 HTTP 服务器上上传文件,但是当我调用它时出现错误 req.GetResponse(); 在客户端代码中

远程服务器返回错误:(405) 方法不允许。

客户端代码

    public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string fileToUpload = Server.MapPath("~/Files/Ricky_Martin_Livin_la.mp3");
string uploadUrl = "http://localhost/soundcheck/uploadfiles.aspx";
//string uploadUrl = "http://10.0.2.2/musicapp/handle_upload.php";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
req.Method = "PUT"; // you might use "POST"
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;

Stream reqStream = req.GetRequestStream();

byte[] inData = new byte[rdr.Length];

// Get data from upload file to inData
int bytesRead = rdr.Read(inData, 0, int.Parse(rdr.Length.ToString()));

// put data into request stream
reqStream.Write(inData, 0, int.Parse(rdr.Length.ToString()));

rdr.Close();
req.GetResponse();

// after uploading close stream
reqStream.Close();
}
}

服务器代码

using System;
using System.Collections;
using System.IO;
using System.Data;
using System.Web;
using System.Text;
using System.Web.Security;

public partial class uploadfiles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
LogInFile("First");
HttpFileCollection uploadFile = Request.Files;
LogInFile("Second");
if (uploadFile.Count > 0)
{
HttpPostedFile postedFile = uploadFile[0];
LogInFile("Thrid");
System.IO.Stream inStream = postedFile.InputStream;
LogInFile("Forth");
byte[] fileData = new byte[postedFile.ContentLength];
LogInFile("Fifth");
inStream.Read(fileData, 0, postedFile.ContentLength);
LogInFile("Sixth");
postedFile.SaveAs(Server.MapPath("Data") + "\\" + postedFile.FileName);
}
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Message : " +ex.Message);
sb.AppendLine("Source : " + ex.Source);
sb.AppendLine("StackTrace : " + ex.StackTrace);
sb.AppendLine("InnerException : " + ex.InnerException);
sb.AppendLine("ToString : " + ex.ToString());

LogInFile(sb.ToString());
}
}
public void LogInFile(string str)
{
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(Server.MapPath("Data") + "\\expfile.txt"))
{
sb.AppendLine("= = = = = =");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
sb.AppendLine();
}
sb.AppendLine(str);
using (StreamWriter outfile = new StreamWriter(Server.MapPath("Data") + "\\expfile.txt"))
{
outfile.Write(sb.ToString());
}
}

}

在服务器代码中我写了这些日志来跟踪是否有任何错误或错误在哪一行。

最佳答案

req.Method = "PUT"; // you might use "POST"

req.Method = "POST"; 

然后再试一次。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com