欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-29 09:20:22
复制代码 代码如下: [httppost] public string uploadimage() { //string ss = request.form["upload...
复制代码 代码如下:

[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;
}
}
}
}