主要场景:图像识别之类的,都需要上传图片,尤其是winform,console等客户端程序
1.单文件/多文件上传 (header头不一样)
使用方法2.1:main
static void Main(string[] args)
{
string path = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "Img");
string filePath = Path.Combine(path, "1.jpg");
string token = "632dcb15425e4b2596728951baf1378c3";
var file = File.ReadAllBytes(filePath);
string url = "https://adc-wechat-ca154-ocr.cognitiveservices.azure.cn/vision/v3.2/ocr?language=unk&detectOrientation=true&model-version=latest";
string result = HttpFileUtil.UploadFile(filePath, token, url);
Console.WriteLine(result);
Console.Read();
//文件流进行上传
WebClient myWebClient = new WebClient();
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] postArray = br.ReadBytes(Convert.ToInt32(fs.Length));
myWebClient.Headers.Add("Content-Type", "application/octet-stream");
myWebClient.Headers.Add("Ocp-Apim-Subscription-Key", token);
var result1 = myWebClient.UploadData(url, "POST", postArray);
string str = Encoding.UTF8.GetString(result1);
Console.WriteLine(str);
}
使用方法2.2:工具类
//工具类
public class HttpFileUtil
{
/// <summary>
/// 单文件上传
/// </summary>
/// <param name="localFilePath"></param>
/// <param name="token"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string UploadFile(string localFilePath, string token, string url)
{
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
try
{
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
myWebClient.Headers.Add("Ocp-Apim-Subscription-Key", token);
var by = myWebClient.UploadFile(url, "POST", localFilePath);
string str = Encoding.UTF8.GetString(by);
return str;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 多文件上传
/// </summary>
/// <param name="localFilePath"></param>
/// <param name="token"></param>
/// <param name="url"></param>
/// <returns></returns>
public static bool UploadFile2(string localFilePath, string token, string url)
{
string uriString;
// 得到文件名,文件扩展名字,服务器路径
// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
try
{
//使用UploadFile方法可以用下面的格式
myWebClient.Headers.Add("Content-Type", "multipart/form-data");//注意头部必须是form-data
myWebClient.Headers.Add("Authorization", token);
var by = myWebClient.UploadFile(url, "POST", localFilePath);
string s = Encoding.UTF8.GetString(by);
}
catch (Exception ex)
{
return false;
}
return true;
}
}