Web Api 实现文件上传

网上找了好久,国内关于Web Api的资料少之又少,园区里面有一篇文章介绍的很详细,可惜是在4.5的环境下实现的:

 

/// <summary>
/// 文件上传
/// </summary>
public class UploadController : BaseController
{ 
   [HttpPost]
public Ret<object> PostUpload() { var httpRequest = HttpContext.Current.Request; List<string> list = new List<string>(); for (int i = 0; i < httpRequest.Files.Count; i++) { var file = httpRequest.Files[i]; if (file.ContentLength < 1 || file == null) continue; //文件存盘,返回Url list.Add(V9.Helper.Attach.Save(file)); } return new Ret<object>() { error = 0, msg = "上传成功!", data = list }; } }

 

 

 

 

转载于:https://www.cnblogs.com/moozhd/archive/2013/01/14/2859937.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用HttpClient类来调用Web API实现文件上传。以下是一个简单的WinForms代码示例: ```csharp using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Windows.Forms; namespace WinFormsFileUpload { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent()) { // 添加文件 var fileContent = new ByteArrayContent(File.ReadAllBytes(textBox1.Text)); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); content.Add(fileContent, "file", Path.GetFileName(textBox1.Text)); // 添加其他参数 var values = new Dictionary<string, string> { { "param1", "value1" }, { "param2", "value2" } }; foreach (var keyValuePair in values) { content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key); } // 发送请求 var response = await client.PostAsync("http://example.com/api/upload", content); if (response.IsSuccessStatusCode) { MessageBox.Show("上传成功!"); } else { MessageBox.Show("上传失败!"); } } } } } } ``` 在上面的示例中,我们使用MultipartFormDataContent类来创建请求正文,然后使用HttpClient类发送请求。请注意,我们还添加了其他参数(param1和param2)作为请求正文的一部分。如果请求成功,我们将显示一个消息框,否则将显示另一个消息框。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值