此Python程序将图片上传到url。我需要同样的东西,但是在C#中。我怎样才能做到这一点?我正在使用赢表格。
程序:
fin = open(file_path, 'rb')
files = {'file': fin}
try:<br>
r = requests.post(url, files=files, verify = False)
finally:
fin.close()
json_data = json.loads(r.text)
答案 0 :(得分:0)
周围有很多示例,但是尝试一下可能对您有用的
private byte[] GetFileByteArray(string filename)
{
FileStream oFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
// Create a byte array of file size.
byte[] FileByteArrayData = new byte[oFileStream.Length];
//Read file in bytes from stream into the byte array
oFileStream.Read(FileByteArrayData, 0, System.Convert.ToInt32(oFileStream.Length));
//Close the File Stream
oFileStream.Close();
return FileByteArrayData; //return the byte data
}
//此方法返回文件的Byte数组,然后您需要调用UploadVideoFile方法。
public string UploadVideoFile(string URL, byte[] VideoFileData)
{
string Response = null;
HttpWebRequest WebReq = null;
HttpWebResponse WebRes = null;
StreamReader StreamResponseReader = null;
Stream requestStream = null;
try
{
WebReq = (HttpWebRequest)WebRequest.Create(URL);
WebReq.Method = "POST";
WebReq.Accept = "*/*";
WebReq.Timeout = 50000;
WebReq.KeepAlive = false;
WebReq.AllowAutoRedirect = false;
WebReq.AllowWriteStreamBuffering = true;
WebReq.ContentType = "binary/octet-stream";
WebReq.ContentLength = VideoFileData.Length;
requestStream = WebReq.GetRequestStream();
requestStream.Write(VideoFileData, 0, VideoFileData.Length);
requestStream.Close();
WebRes = (HttpWebResponse)WebReq.GetResponse();
StreamResponseReader = new StreamReader(WebRes.GetResponseStream(), Encoding.UTF8);
Response = StreamResponseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
if (WebReq != null)
{
WebReq.Abort();
WebReq = null;
}
if (WebRes != null)
{
WebRes.Close();
WebRes = null;
}
if (StreamResponseReader != null)
{
StreamResponseReader.Close();
StreamResponseReader = null;
}
if (requestStream != null)
{
requestStream = null;
}
}
return Response;
}