C# 最齐全的上传图片方法
程序员文章站
2022-04-01 09:10:16
方法里包括了图片大小限制、图片尺寸、文件内容等等的判断。。。
该案例是mvc下的demo,支持单张图片上传。
public actionresult uploa...
方法里包括了图片大小限制、图片尺寸、文件内容等等的判断。。。
该案例是mvc下的demo,支持单张图片上传。
public actionresult upload() { string imgurl = ""; foreach (string key in request.files) { //这里只测试上传第一张图片file[0] httppostedfilebase file0 = request.files[key]; //转换成byte,读取图片mime类型 stream stream; int size = file0.contentlength / 1024; //文件大小kb if (size > 1024) { return content(returnmsg(enum_return.失败, "图片不能超过1m:", null)); } byte[] filebyte = new byte[2];//contentlength,这里我们只读取文件长度的前两位用于判断就好了,这样速度比较快,剩下的也用不到。 stream = file0.inputstream; stream.read(filebyte, 0, 2);//contentlength,还是取前两位 //获取图片宽和高 //system.drawing.image image = system.drawing.image.fromstream(stream); //int width = image.width; //int height = image.height; string fileflag = ""; if (filebyte != null && filebyte.length > 0)//图片数据是否为空 { fileflag = filebyte[0].tostring() filebyte[1].tostring(); } string[] filetypestr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,gif,bmp,png if (filetypestr.contains(fileflag)) { string action = request["action"]; string path = "/uploads/"; switch (action) { case "headimage": path = "headimage/"; break; case "blogtype": path = "blogtype/"; break; } string fullpath = path userinfo.userid "/"; if (!directory.exists(server.mappath(fullpath))) { directory.createdirectory(server.mappath(fullpath)); } request.files[key].saveas(server.mappath(fullpath request.files[key].filename)); imgurl = fullpath request.files[key].filename; } else { return content(returnmsg(enum_return.失败, "图片格式不正确:" fileflag, null)); } stream.close(); } return content(returnmsg(enum_return.成功, "上传成功", imgurl)); }
一般处理程序
public void processrequest(httpcontext context) { context.response.contenttype = "application/json"; httppostedfile _upfile = context.request.files["file"]; if (_upfile.contentlength < 500000) { if (string.isnullorempty(_upfile.filename)) { context.response.write("请上传图片"); } string filefullname = _upfile.filename; string dataname = datetime.now.tostring("yyyymmddhhmmss"); string filename = filefullname.substring(filefullname.lastindexof("\\") 1); string type = filefullname.substring(filefullname.lastindexof(".") 1); if (type == "bmp" || type == "jpg" || type == "gif" || type == "jpg" || type == "bmp" || type == "gif") { _upfile.saveas(httpcontext.current.server.mappath("photo") "\\" dataname "." type); httpcookie cookie = new httpcookie("photo"); context.response.write("上传成功"); } else { context.response.write("支持格式:|jpg|gif|bmp|"); } } else { context.response.write("你的图片已经超过500k的大小!"); } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!