這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)如何在C# 項(xiàng)目中利用HttpClient實(shí)現(xiàn)一個(gè)文件上傳功能,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

HttpClient和MultipartFormDataContent(傳送門(mén))最低適用于.NET Framework 4.5版本
using (HttpClient client = new HttpClient())
{
var content = new MultipartFormDataContent();
//添加字符串參數(shù),參數(shù)名為qq
content.Add(new StringContent("123456"), "qq");
string path = Path.Combine(System.Environment.CurrentDirectory, "1.png");
//添加文件參數(shù),參數(shù)名為files,文件名為123.png
content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "123.png");
var requestUri = "http://192.168.1.108:56852/api/Test/SaveFile";
var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}[HttpPost]
public async Task<JsonResult> SaveFile([FromForm]string qq, IFormFile file)
{
return await Task.Run(() =>
{
try
{
//保存文件到本地
var filefullPath = Path.Combine(Directory.GetCurrentDirectory(), file.FileName);
using (FileStream fs = new FileStream(filefullPath, FileMode.Create))
{
file.CopyTo(fs);
fs.Flush();
}
}
catch (Exception ex)
{
return Fail(file.FileName + "---" + ex.Message);
}
return Success();
});
}注意:如果要通過(guò)參數(shù)形式接收數(shù)據(jù),需要確保參數(shù)名稱和上面發(fā)送請(qǐng)求中設(shè)置的名稱一致,否則無(wú)法自動(dòng)綁定到參數(shù)中,且需要給參數(shù)加上[FromForm]的標(biāo)記。
public class SaveFileModel
{
public string qq { get; set; }
public IFormFile File { get; set; }
}
public async Task<JsonResult> SaveFile([FromForm]SaveFileModel model)
{
//......
}public async Task<JsonResult> SaveFile()
{
return await Task.Run(() =>
{
var files = HttpContext.Request.Form.Files;
var qq = HttpContext.Request.Form["qq"];
//......
});
}上述就是小編為大家分享的如何在C# 項(xiàng)目中利用HttpClient實(shí)現(xiàn)一個(gè)文件上傳功能了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
新聞名稱:如何在C#項(xiàng)目中利用HttpClient實(shí)現(xiàn)一個(gè)文件上傳功能-創(chuàng)新互聯(lián)
轉(zhuǎn)載來(lái)源:http://www.chinadenli.net/article34/iiepe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開(kāi)發(fā)、微信小程序、網(wǎng)站排名、網(wǎng)站營(yíng)銷(xiāo)、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站改版
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容