加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#保存上传来的图片示例代码

发布时间:2020-12-15 04:15:51 所属栏目:百科 来源:网络整理
导读:复制代码 代码如下: [HttpPost] public string UploadImage() { //string ss = Request.Form["uploadFile"]; //return ss; HttpPostedFileBase uploadFile = Request.Files[0]; string fileName = uploadFile.FileName; int fileSize = uploadFile.ContentLe
复制代码 代码如下:

[HttpPost]
public string UploadImage()
{
//string ss = Request.Form["uploadFile"];
//return ss;
HttpPostedFileBase uploadFile = Request.Files[0];
string fileName = uploadFile.FileName;
int fileSize = uploadFile.ContentLength;
string fileExt = Path.GetExtension(fileName).ToLower();
string message = "";
if (!(fileExt == ".png" || fileExt == ".gif" || fileExt == ".jpg" || fileExt == ".jpeg"))
{
message = "图片类型只能为gif,png,jpg,jpeg";
return message;
}
else
{
if (fileSize > (int)(500 * 1024))
{
message = "图片大小不能超过500KB";
return message;
}
else
{
Random r = new Random();
string uploadFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + r.Next(100000,999999) + fileExt;
try
{
string directoryPath = Server.MapPath("~/UploadImages/");
if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹
{
Directory.CreateDirectory(Server.MapPath("~/UploadImages/"));
}
uploadFile.SaveAs(Server.MapPath("~/UploadImages/") + uploadFileName);
message = uploadFileName;
return message;
}
catch (Exception ex)
{
message = ex.Message;
return message;
}
}
}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读