十年河东,十年河西,莫欺少年穷
学无止境,精益求精
代码篇,不多说
如下:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http; namespace FileUp.Controllers
{
public class FileController : ApiController
{
[HttpPost]
public async Task<string> UploadFileStream()
{
string returns = string.Empty;
string fileType = "ss";//要创建的子文件夹的名字
var uploadPath = "~/upload";
string filePath = System.Web.HttpContext.Current.Server.MapPath(uploadPath + "/" + fileType + "/");//绝对路径
//string filePath = uploadPath + "\\" + fileType + "\\"; //E:\Fileup 居家
if (Directory.Exists(filePath) == false)
{
Directory.CreateDirectory(filePath);
} try
{
var provider = new ReNameMultipartFormDataStreamProvider(filePath); await Request.Content.ReadAsMultipartAsync(provider).ContinueWith(o =>
{ foreach (var file in provider.FileData)
{
string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');//待上传的文件名
FileInfo fileinfo = new FileInfo(file.LocalFileName);
//判断开始
int maxSize = ;
string oldName = orfilename;//选择的文件的名称
if (fileinfo.Length <= )
{
//文件大小判断 未选择上传的图片 大小为零
}
else if (fileinfo.Length > maxSize)
{
//文件大小判断 上传文件是否超限制
}
else
{
//
string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
string Extension = fileExt;
string CreateTime = DateTime.Now.ToString("yyyyMMddHHmmss"); //定义允许上传的文件扩展名
String fileTypes = "gif,jpg,jpeg,png,bmp";
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring().ToLower()) == -)
{ returns = "上传的文件格式不是图片";
}
else
{
returns = string.Format(@"/Uploads/{0}/{1}", fileType, System.IO.Path.GetFileName(file.LocalFileName));
}
}
}
});
}
catch (Exception ex)
{
returns = ex.ToString();
}
return returns;
} /// <summary>
/// 重命名上传的文件
/// </summary>
public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public ReNameMultipartFormDataStreamProvider(string root)
: base(root)
{ } public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{ string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
return Guid.NewGuid().ToString().Replace("-", "") + extension;
} private string GetValidFileName(string filePath)
{
char[] invalids = System.IO.Path.GetInvalidFileNameChars();
return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
} }
}
}
PostMan请求如下:
@陈卧龙的博客