ASP.net WebAPI 上传图片实例
程序员文章站
2024-02-26 14:31:28
复制代码 代码如下:[httppost] public task imgupload() { //...
复制代码 代码如下:
[httppost]
public task<hashtable> imgupload()
{
// 检查是否是 multipart/form-data
if (!request.content.ismimemultipartcontent("form-data"))
throw new httpresponseexception(httpstatuscode.unsupportedmediatype);
//文件保存目录路径
string savetemppath = "~/sayplaces/" + "/saypic/saypictemp/";
string dirtemppath = httpcontext.current.server.mappath(savetemppath);
// 设置上传目录
var provider = new multipartformdatastreamprovider(dirtemppath);
//var queryp = request.getquerynamevaluepairs();//获得查询字符串的键值集合
var task = request.content.readasmultipartasync(provider).
continuewith<hashtable>(o =>
{
hashtable hash = new hashtable();
hash["error"] = 1;
hash["errmsg"] = "上传出错";
var file = provider.filedata[0];//provider.formdata
string orfilename = file.headers.contentdisposition.filename.trimstart('"').trimend('"');
fileinfo fileinfo = new fileinfo(file.localfilename);
//最大文件大小
int maxsize = 10000000;
if (fileinfo.length <= 0)
{
hash["error"] = 1;
hash["errmsg"] = "请选择上传文件。";
}
else if (fileinfo.length > maxsize)
{
hash["error"] = 1;
hash["errmsg"] = "上传文件大小超过限制。";
}
else
{
string fileext = orfilename.substring(orfilename.lastindexof('.'));
//定义允许上传的文件扩展名
string filetypes = "gif,jpg,jpeg,png,bmp";
if (string.isnullorempty(fileext) || array.indexof(filetypes.split(','), fileext.substring(1).tolower()) == -1)
{
hash["error"] = 1;
hash["errmsg"] = "上传文件扩展名是不允许的扩展名。";
}
else
{
string ymd = datetime.now.tostring("yyyymmdd", system.globalization.datetimeformatinfo.invariantinfo);
string newfilename = datetime.now.tostring("yyyymmddhhmmss_ffff", system.globalization.datetimeformatinfo.invariantinfo);
fileinfo.copyto(path.combine(dirtemppath, newfilename + fileext), true);
fileinfo.delete();
hash["error"] = 0;
hash["errmsg"] = "上传成功";
}
}
return hash;
});
return task;
}
下一篇: git status命令