复制代码 代码如下:
[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;
}
}
}
}
[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;
}
}
}
}
标签:
C#,保存上传图片
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com
暂无“C#保存上传来的图片示例代码”评论...