项目场景:APP 端需要上传图片文件,并且需要携带一些相关的参数;
服务端使用 ASP.NET WebAPI,MultipartFormDataStreamProvider 接收参数,MultipartMemoryStreamProvider 接收文件
有文件上传时使用 Content-Type: multipart/form-data 的类型请求
【注意:Headers 中千万不要添加 Content-Type: application/json 否则接收不到参数】
postman 工具请求参数实例
POST /api/StudentLeave/Create
Host: localhost:52644
Cache-Control: no-cache
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Controller接收参数
[HttpPost]
public async Task Create()
{
string gradeId = HttpContext.Current.Request["GradeId"];
string classId = HttpContext.Current.Request["ClassId"];
string studentId = HttpContext.Current.Request["StudentId"];
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
string root = HttpContext.Current.Server.MapPath(StringPlus.GetWebConfigKey("APIClassBannerPath"));
var providerForm = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(providerForm);
Dictionary dic = new Dictionary();
foreach (var key in providerForm.FormData.AllKeys)
{
//接收FormData
dic.Add(key, providerForm.FormData[key]);
}
var jsonString = JsonConvert.SerializeObject(dic, Formatting.Indented);
StudentLeaveRequest studentLeaveModel = JsonConvert.DeserializeObject(jsonString);
var provider = new MultipartMemoryStreamProvider();
foreach (var file in provider.Contents)
{
if (!string.IsNullOrEmpty(file.Headers.ContentDisposition.FileName))
{
UpfileDto upfile = new UpfileDto();
FileInfo fileinfo = new FileInfo(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
string filename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
//string filename = file.Headers.ContentDisposition.Name.Replace("\"", "");
string fileExtension = Path.GetExtension(filename).ToLower();//文件的后缀名(小写)
filename = $"{DateTime.Now.ToString("yyyyMMddHHmmss.fff")}{fileExtension}";
if (string.IsNullOrEmpty(filename))
filename = $"{DateTime.Now.ToString("yyyyMMddHHmmss.fff")}{fileExtension}";
var ms = file.ReadAsStreamAsync().Result;
using (var br = new BinaryReader(ms))
{
System.Drawing.Image oImage = System.Drawing.Image.FromStream(ms);
oImage.Save(upfile.OFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
===============================
[HttpPost]
public async Task Create()
{
List list = new List();
try
{
//if (!Request.Content.IsMimeMultipartContent())
// throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 234");
string root = HttpContext.Current.Server.MapPath(StringPlus.GetWebConfigKey("APIStudentLeavePath"));
#region StudentLeave 操作
string posterType = HttpContext.Current.Request["PosterType"];
string leaveType = HttpContext.Current.Request["LeaveType"];
string locationType = HttpContext.Current.Request["LocationType"];
string gradeId = HttpContext.Current.Request["GradeId"];
string classId = HttpContext.Current.Request["ClassId"];
string teacherId = HttpContext.Current.Request["TeacherId"];
string studentParentId = HttpContext.Current.Request["StudentParentId"];
string studentId = HttpContext.Current.Request["StudentId"];
string subject = HttpContext.Current.Request["Subject"];
string content = HttpContext.Current.Request["Content"];
string startTime = HttpContext.Current.Request["StartTime"];
string endTime = HttpContext.Current.Request["EndTime"];
string reason = HttpContext.Current.Request["Reason"];
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 251");
StudentLeaveRequest request = new StudentLeaveRequest();
request.Id = StringPlus.GenerateGuid();
request.PosterType = Convert.ToInt32(posterType);
request.LeaveType = leaveType;
request.LocationType = Convert.ToInt32(locationType);
request.GradeId = gradeId;
request.ClassId = classId;
request.TeacherId = teacherId;
request.StudentParentId = studentParentId;
request.StudentId = studentId;
request.Subject = subject;
request.Content = content;
request.SchoolId = schoolId;
request.StartTime = Convert.ToDateTime(startTime);
request.EndTime = Convert.ToDateTime(endTime);
request.Reason = reason;
request.Approver = string.Empty;
request.ApprovalStatus = (int)EnumApprovalStatus.UnderApproval;
//request.CreatedBy = string.Empty;
//request.ModifyBy = string.Empty;
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 272");
if (!_relationRepo.IsExistRelation(studentId, studentParentId, schoolId))
{
return ReturnResult((int)CodeEnum.Fail, "学生与家长未建立亲属关系,不能申请请假");
}
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 277");
_studentLeaveRepo.Add(Mapper.Map(request));
#endregion
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 281");
#region 发送通知
var student = _userInfoRepo.FindFirst(x => x.Id == studentId && x.Status != "D");
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 284");
string studentName = "";
if (student != null)
{
studentName = student.RealName;
}
string strlocationType = "";
switch (request.LocationType)
{
case 1:
strlocationType = "校内";
break;
case 2:
strlocationType = "校外";
break;
case 3:
strlocationType = "宿舍外";
break;
}
string strLeaveType = "";
switch (request.LeaveType)
{
case "2":
strLeaveType = "事假";
break;
case "3":
strLeaveType = "病假";
break;
}
//var parent = _userInfoRepo.FindFirst(x => x.Id == studentParentId && x.Status != "D");
//string parentMobile = "";
//if (parent != null)
//{
// parentMobile = parent.Mobile;
//}
var teacher = _userInfoRepo.FindFirst(x => x.Id == teacherId && x.Status != "D");
string teacherMobile = "";
if (teacher != null)
{
teacherMobile = teacher.Mobile;
}
if (!string.IsNullOrEmpty(teacherMobile))
{
string extParams = "{ \"LeaveId\":" + "\"" + request.Id + "\"}";
AliPushUtil.AccessKeyId = _accessKeyId;
AliPushUtil.AccessKeySecret = _accessKeySecret;
AliPushUtil.AndroidAppKey = _androidAppKey;
AliPushUtil.IOSAppKey = _iOSAppKey;
AliPushUtil.TargetValue = teacherMobile;
AliPushUtil.Initial();
string strBody = $"{studentName}{strlocationType}{strLeaveType} {startTime}至{endTime}";
AliPushUtil.Push("ALIAS", "NOTICE", "您有一个新的请假通知", strBody, extParams, "DEV", "", "NONE", "", "");
}
#endregion
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 342");
#region 上传图片
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 344");
if (Request.Content.IsMimeMultipartContent())
{
var provider = new MultipartMemoryStreamProvider();
StringBuilder sb = new StringBuilder();
await Request.Content.ReadAsMultipartAsync(provider);
int fileTotal = 0;
foreach (var file in provider.Contents)
{
if (file.Headers.ContentType != null
&& (file.Headers.ContentType.MediaType == "image/jpeg"
|| file.Headers.ContentType.MediaType == "image/png"
|| file.Headers.ContentType.MediaType == "image/bmp"
|| file.Headers.ContentType.MediaType == "image/gif"))
{
fileTotal += 1;
}
}
if (fileTotal < 10)
{
}
else
{
return ReturnResult(-302, "超过允许的图片数量范围");
}
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 371");
foreach (var file in provider.Contents)
{
if (!string.IsNullOrEmpty(file.Headers.ContentDisposition.FileName))
{
UpfileDto upfile = new UpfileDto();
FileInfo fileinfo = new FileInfo(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
string filename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
//string filename = file.Headers.ContentDisposition.Name.Replace("\"", "");
string fileExtension = Path.GetExtension(filename).ToLower();//文件的后缀名(小写)
filename = $"{DateTime.Now.ToString("yyyyMMddHHmmss.fff")}{fileExtension}";
if (string.IsNullOrEmpty(filename))
filename = $"{DateTime.Now.ToString("yyyyMMddHHmmss.fff")}{fileExtension}";
var ms = file.ReadAsStreamAsync().Result;
using (var br = new BinaryReader(ms))
{
if (ms.Length <= 0 || ms.Length >= 3000000)
{
return ReturnResult(0, "指定的文件大小不符合要求!");
}
#region 生成原图(不保存)
System.Drawing.Image oImage = System.Drawing.Image.FromStream(ms);
int owidth = oImage.Width; //原图宽度
int oheight = oImage.Height; //原图高度
int LimitWidth = 3072;
int LimitHeight = 2304;
int twidth = 300;
int theight = 300;
string OFileName = "0";
string TFileName = "0";
if (owidth > LimitWidth || oheight > LimitHeight)
return ReturnResult(0, "超过允许的图片尺寸范围!");
if (owidth >= twidth || oheight >= theight)
{
//按比例计算出缩略图的宽度和高度
if (owidth >= oheight)
theight = (int)Math.Floor(Convert.ToDouble(oheight) * (Convert.ToDouble(twidth) / Convert.ToDouble(owidth)));//等比设定高度
else
twidth = (int)Math.Floor(Convert.ToDouble(owidth) * (Convert.ToDouble(theight) / Convert.ToDouble(oheight)));//等比设定宽度
}
else
{
theight = oheight;
twidth = owidth;
}
var data = br.ReadBytes((int)ms.Length);
#endregion
OFileName = "o" + filename;
TFileName = "t" + filename;
string SavePath = HttpContext.Current.Server.MapPath(StringPlus.GetWebConfigKey("APIStudentLeavePath"));
upfile.OFullName = SavePath + OFileName;
upfile.TFullName = SavePath + TFileName;
#region 保存图片
switch (fileExtension)
{
case ".jpeg":
case ".jpg":
{
oImage.Save(upfile.OFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
}
case ".gif":
{
oImage.Save(upfile.OFullName, System.Drawing.Imaging.ImageFormat.Gif);
break;
}
case ".png":
{
oImage.Save(upfile.OFullName, System.Drawing.Imaging.ImageFormat.Png);
break;
}
case ".bmp":
{
oImage.Save(upfile.OFullName, System.Drawing.Imaging.ImageFormat.Bmp);
break;
}
}
list.Add(new AttachmentDto
{
Id = Guid.NewGuid().ToString(),
AttType = (int)EnumAttachmentType.StudentLeave,
AttNo = request.Id,
FileType = (int)EnumFileType.Image,
FileName = OFileName,
Path = $"{StringPlus.GetWebConfigKey("APIStudentLeavePath")}{OFileName}",
SchoolId = schoolId,
Status = "A"
});
#endregion
}
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 475");
}
}
}
#endregion
}
catch (Exception ex)
{
logger.Error("StudentLeaveController CreateStudentLeaveResponse Ln 482" + ex.Message);
return ReturnResult(500, "服务器无响应" + ex.Message);
}
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 488");
_attachmentRepo.BatchInsert(Mapper.Map>(list));
logger.Info("StudentLeaveController CreateStudentLeaveResponse Ln 490");
return new CreateStudentLeaveResponse { };
}
3、
4、
5、
6、
7、
8、
9、
0、