前言: 这几天在做一个图片上传的API,在网上找了很多资料,也学到了很多东西,最近刚接触WebAPI,好多东西都看不懂。 还停留在webfrom的概念, 哈哈 其实webfrom也没学好,废话不多说了,先看代码。
public async Task<HttpResponseMessage> PostUpload(string Token, int Part)
{
if (Global.checkToken(Token)) //验证口令通过
{
// Check whether the POST operation is MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
// Prepare CustomMultipartFormDataStreamProvider in which our multipart form
// data will be loaded.
string partFolder = string.Empty;
switch (Part)
{
case 1:
partFolder = "MobileUploadImages_BaoGao";
break;
case 2:
partFolder = "MobileUploadImages_ShenQing";
break;
case 3:
partFolder = "MobileUploadImages_RenWu";
break;
default:
partFolder = "MobileUploadImages_QiTa";
break;
}
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/"+ImageUploadPublic.FoldersAddress+"/"+partFolder);
if (!Directory.Exists(fileSaveLocation))
Directory.CreateDirectory(fileSaveLocation);
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await Request.Content.ReadAsMultipartAsync(provider);
string newFileName = string.Empty;
foreach (MultipartFileData file in provider.FileData)
{
newFileName = Path.GetFileName(file.LocalFileName);
files.Add(newFileName);
}
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
else
{
string ResCode = "0002", Msg = "口令错误";
Dictionary<string, object> obj = new Dictionary<string, object>();
obj.Add("ResCode", ResCode);
obj.Add("Msg", Msg);
return Request.CreateResponse(HttpStatusCode.OK, obj);
}
}
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
//修改图片名称并返回
string newFileName = string.Empty;
newFileName = Path.GetExtension(headers.ContentDisposition.FileName.Replace("\"", string.Empty));//获取后缀名
newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(0, 99999) + newFileName;
return newFileName;
}
}
上面两块代码就能实现图片批量上传功能, 下面是测试接口的代码:
static void Main(string[] args)
{
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
// Make sure to change API address
client.BaseAddress = new Uri("http://localhost:18110/");
// Add first file content
var fileContent1 = new ByteArrayContent(File.ReadAllBytes(@"C:\Users\y\Desktop\testImgUpload\wokechakandehuibao.jpg"));
fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "wokechakandehuibao.jpg"
};
// Add Second file content
var fileContent2 = new ByteArrayContent(File.ReadAllBytes(@"C:\Users\y\Desktop\testImgUpload\xiezhoubaoFasongrenyuan.jpg"));
fileContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "xiezhoubaoFasongrenyuan.jpg"
};
content.Add(fileContent1);
content.Add(fileContent2);
// Make a call to Web API
var result = client.PostAsync("/WebAppErpUser/PostUpload?Token=000000&Part=1", content).Result;
//HttpContent hc = result.Content;
result.Content.ReadAsStringAsync().ContinueWith((str) => { Console.WriteLine(str.Result); });//输出上传的图片名称(修改后的)
Console.WriteLine(result.StatusCode);
Console.ReadLine();
}
}
其实网上有很多上传图片的web api 代码,只是没有找到适合我的,结果到头来找到这段代码基本实现了我的需求,所以就用这个了,然后自己再改吧改吧,就这样了。
这一段代码是我在网上找的,具体在哪个网站找的我也忘了,其中添加了修改图片名称的功能,其他没啥,只为复制代码的同学提供方便。
注:如果原创者看到了这个博文,请原谅我没有记住你的名字,请原谅我没有收藏你的博客。