1 在一般处理程序中写接口,上传方法
```csharp
private void UserUploadImg2(HttpContext context)
{
string returnValue = "";
HttpPostedFile _upfile = context.Request.Files[0];
long lngUploadFileSize = _upfile.ContentLength;//byte 文件大小
if (_upfile == null)
{
returnValue = "{\"status\": \"-1\",\"msg\": \"上传文件为空,请重试!\"}";
ResponseWriteEnd(context, returnValue);
}
else
{
string Thumb = string.Empty;
string fileName = _upfile.FileName;
string fileType = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();//图片后缀
string strTypeDir = "";
ImageInfo othumb;
bool blnIsFileTypeValid = false;
int intFileTypeId = 0;
switch (fileType)
{
//音频 .mp3
case "mp3":
strTypeDir = "voice";
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Voice;
break;
//图片
case "jpg":
case "jpeg":
case "gif":
case "png":
case "bmp":
strTypeDir = "img";
othumb = new ImageInfo();
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Picture;
break;
//视频
case "3gp":
case "flv":
case "mp4":
strTypeDir = "video";
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Video;
break;
//文本
case "txt":
case "doc":
case "docx":
case "ppt":
case "pptx":
case "xls":
case "xlsx":
case "pdf":
strTypeDir = "word";
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Word;
break;
default:
strTypeDir = "attach";
returnValue = "{\"status\": \"-1\",\"msg\": \"您上传的文件格式不正确!\"}";
ResponseWriteEnd(context, returnValue);
break;
}
//验证格式
if (!blnIsFileTypeValid)
{
returnValue = "{\"status\": \"-1\",\"msg\": \"您上传的文件格式不正确!\"}";
ResponseWriteEnd(context, returnValue);
}
int intUploadLimimtSize = 0;
//根据配置文件,验证上传文件大小
if (intUploadLimimtSize > 0)
{
if (lngUploadFileSize > (intUploadLimimtSize * 1024))
{
returnValue = "{\"status\": \"-1\",\"msg\": \"上传文件大小超过系统设置,此类型作品上传不能超过!\"}";
ResponseWriteEnd(context, returnValue);
}
}
string strSavePath = "";
if (strTypeDir != "")
{
strSavePath = "/uploads/res/" + strTypeDir + "/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";
}
else
{
strSavePath = "/uploads/res/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";
}
string imagesPath = HttpContext.Current.Server.MapPath(strSavePath);//保存图片
if (!System.IO.Directory.Exists(imagesPath))
{
System.IO.Directory.CreateDirectory(imagesPath);
}
string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
var saveName = strSavePath + strNowTimeString + "." + fileType;//图片地址,半路径
_upfile.SaveAs(HttpContext.Current.Server.MapPath(saveName));//保存图片
returnValue = "{\"status\": \"0\" ,\"msg\": \"上传成功!\",\"src\":\"" + saveName + "\" }";
ResponseWriteEnd(context, returnValue);
}
}
private void UserUploadImg2(HttpContext context)
{
string returnValue = "";
HttpPostedFile _upfile = context.Request.Files[0];
long lngUploadFileSize = _upfile.ContentLength;//byte 文件大小
if (_upfile == null)
{
returnValue = "{\"status\": \"-1\",\"msg\": \"上传文件为空,请重试!\"}";
ResponseWriteEnd(context, returnValue);
}
else
{
string Thumb = string.Empty;
string fileName = _upfile.FileName;
string fileType = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();//图片后缀
string strTypeDir = "";
ImageInfo othumb;
bool blnIsFileTypeValid = false;
int intFileTypeId = 0;
switch (fileType)
{
//音频 .mp3
case "mp3":
strTypeDir = "voice";
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Voice;
break;
//图片
case "jpg":
case "jpeg":
case "gif":
case "png":
case "bmp":
strTypeDir = "img";
othumb = new ImageInfo();
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Picture;
break;
//视频
case "3gp":
case "flv":
case "mp4":
strTypeDir = "video";
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Video;
break;
//文本
case "txt":
case "doc":
case "docx":
case "ppt":
case "pptx":
case "xls":
case "xlsx":
case "pdf":
strTypeDir = "word";
blnIsFileTypeValid = true;
intFileTypeId = (int)UploadFileTypeEnum.Word;
break;
default:
strTypeDir = "attach";
returnValue = "{\"status\": \"-1\",\"msg\": \"您上传的文件格式不正确!\"}";
ResponseWriteEnd(context, returnValue);
break;
}
//验证格式
if (!blnIsFileTypeValid)
{
returnValue = "{\"status\": \"-1\",\"msg\": \"您上传的文件格式不正确!\"}";
ResponseWriteEnd(context, returnValue);
}
int intUploadLimimtSize = 0;
//根据配置文件,验证上传文件大小
if (intUploadLimimtSize > 0)
{
if (lngUploadFileSize > (intUploadLimimtSize * 1024))
{
returnValue = "{\"status\": \"-1\",\"msg\": \"上传文件大小超过系统设置,此类型作品上传不能超过!\"}";
ResponseWriteEnd(context, returnValue);
}
}
string strSavePath = "";
if (strTypeDir != "")
{
strSavePath = "/uploads/res/" + strTypeDir + "/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";
}
else
{
strSavePath = "/uploads/res/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";
}
string imagesPath = HttpContext.Current.Server.MapPath(strSavePath);//保存图片
if (!System.IO.Directory.Exists(imagesPath))
{
System.IO.Directory.CreateDirectory(imagesPath);
}
string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
var saveName = strSavePath + strNowTimeString + "." + fileType;//图片地址,半路径
_upfile.SaveAs(HttpContext.Current.Server.MapPath(saveName));//保存图片
returnValue = "{\"status\": \"0\" ,\"msg\": \"上传成功!\",\"src\":\"" + saveName + "\" }";
ResponseWriteEnd(context, returnValue);
}
}
2 在webapi写接口,上传方法
[AcceptVerbs("GET", "POST")]
[Route("ImgUpload")]
[ResponseType(typeof(ReturnResult))]
public HttpResponseMessage ImgUpload()
{
ReturnResult2 result = new ReturnResult2() { code = "", msg = "", total = 0 };
HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
HttpRequestBase request = context.Request;//定义传统request对象
try
{
var files = request.Files;
if (files.Count > 0)
{
var dir = context.Request["dir"];
string imgNametime = DateTime.Now.ToString("yyyyMMdd");
string Path = "/";
var src = "";
if (!string.IsNullOrEmpty(dir))
{
Path += dir.Trim('/') + "/";
}
var PathNew = Path + imgNametime + "/";
List<string> listSrc = new List<string>();
//如果是多文件,循环
for (int i = 0; i < files.Count; i++)
{
var File2 = files[i];
string FileNamef = File2.FileName; //上传的原文件名
string[] strSpil2 = File2.FileName.Split('.');//将此地址用.号进行分割(img/1.jpg)
string strEnd2 = strSpil2[strSpil2.Length - 1].ToLower();//得到后面的
string imgName = Guid.NewGuid().ToString().Replace("-", "") + "." + strEnd2;
if (FileNamef != null && FileNamef != "")
{
//创建文件夹
string imagesPath = HttpContext.Current.Server.MapPath(PathNew);
if (!System.IO.Directory.Exists(imagesPath))
System.IO.Directory.CreateDirectory(imagesPath);
File2.SaveAs(imagesPath + imgName); //保存操作
src = PathNew + imgName;//图片保存路径
listSrc.Add(src);
}
else
{
result.code = "10001";
result.msg = "操作失败";
return SQLBase.toJson(result);
}
}
result.data = listSrc;
result.code = "10000";
result.msg = "操作成功";
return SQLBase.toJson(result);
}
else
{
result.code = "10001";
result.msg = "操作失败,未接收到上传文件";
return SQLBase.toJson(result);
}
}
catch (Exception ex)
{
result.code = "10002";
result.msg = "获取失败,程序异常";
result.data = null;
log = LogFactory.GetLogger(this.GetType().ToString());
log.Error(ex.LogErrorTxt());
}
return SQLBase.toJson(result);
}
————————————————
版权声明:本文为CSDN博主「zhang123csdn」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhang123csdn/article/details/123503636