--我此处做接口使用,返回所有图片地址给第三方,他随机提取其中一张
public string GetQRCode()
{
int @int = GameRequest.GetInt("userid", 0);
string result;
try
{
JArray ja = new JArray(); //定义一个数组
string info = string.Empty;
var path1 = System.AppDomain.CurrentDomain.BaseDirectory;//获取程序集目录
string path = Path.Combine(path1, "images", "QRCode");//Path.Combine 将3个字符串组合成路径 x/xxx/images/QRCode
var images = Directory.GetFiles(path, ".", SearchOption.AllDirectories).Where(s => s.EndsWith(".png") || s.EndsWith(".jpg"));
//images = Directory.GetFiles(path, "*.png|*.jpg", SearchOption.AllDirectories);
//Directory.GetFiles 返回指定目录的文件路径 SearchOption.AllDirectories 指定搜索当前目录及子目录
//遍历string 型 images数组
foreach (var i in images)
{
var str = i.Replace(path1, "");//获取相对路径
var path2 = str.Replace("\\", "/");//将字符“\\”转换为“/”
ja.Add(path2);
}
info = Newtonsoft.Json.JsonConvert.SerializeObject(ja);//序列化为String
result = JsonHelper.SerializeObject(new
{
Code = 0,
Data = info
});
}
catch (Exception ex)
{
result = JsonHelper.SerializeObject(new
{
Code = 1,
Msg = ex.Message
});
}
return result;
}
-------后台对图片进行增加删除
1,后台获取图片信息 (MVC)
前端:
--script
var postData = {};//搜索条件
$(document).ready(function () {
docReady();
$("#btnDelete").click(function () {
var cid = GetSelectValues();
if (cid == "") { alert("未选中任何数据"); return; }
var data = {};
data.cid = cid;
AjaxSubmit("/Filled/DeletePayQRCode", data, callBack, "del"); });
$("#btnInsert").click(function () {
openWindowOwn('/Filled/AddPayQRCode', '0000', 600, 520) }); });
function docReady() { //加载数据
postData.pageSize = parseInt($("#pagecount").val());
postData.pageIndex = 1; AjaxSearch(postData); }
//搜索事件 function AjaxSearch(postData) { $('#pagin').paging("/Filled/GetPayQRCode", postData, CreatTableBody, postData.pageIndex); }
//绑定数据 function CreatTableBody(jsondata, pageTotal, pageCount, pageIndex, msg) {
var html = "";
if (jsondata != null && jsondata.length > 0) {
$.each(jsondata, function (i, item) {
html += stringFormat("
"); "; }); }html += stringFormat("
{0} ", (item.QRCodeName != "" ? "" : ""));html += stringFormat("
{0} ", item.QRCodeName);html += stringFormat("
{0} ", item.QRCodeUrl);html += stringFormat("
{0} ", (item.QRCodeImgUrl != "" ? " " : "")); html += "$("#DataTables_Table_0_wrapper tbody").html(html); //
$("#DataTables_Table_0_info").html(stringFormat("显示 {0} 至 {1} 共 {2} 条", ((pageIndex - 1) * postData.pageSize + 1), ((pageIndex * postData.pageSize) < pageTotal ? (pageIndex * postData.pageSize) : pageTotal), pageTotal)); }
//回调函数 function callBack(jsonData, fname) { switch (fname) { case "del": alert(jsonData.Msg); window.location.reload(); //window.opener.location.reload(); break; } }
//字符串格式化 function stringFormat() { if (arguments.length == 0) return null; var str = arguments[0]; for (var i = 1; i < arguments.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, arguments[i]); } return str; }
--后端 FilledController.cs
#region 二维码管理
///
/// 二维码管理
///
///
[CheckCustomer]
public ActionResult PayQRCode()
{
return View();
}
///
/// 获取二维码
///
///
[CheckCustomer]
[AntiSqlInjection]
public JsonResult GetPayQRCode()
{
int pageIndex = TypeUtil.ObjectToInt(base.Request["pageIndex"], 1);
int pageSize = TypeUtil.ObjectToInt(base.Request["pageSize"], 10);
int num = TypeUtil.ObjectToInt(base.Request["Type"]);
try
{
JArray ja = new JArray(); //定义一个数组
DataTable dt = new DataTable();
dt.Columns.Add("QRCodeName", typeof(string));
dt.Columns.Add("QRCodeUrl", typeof(string));
dt.Columns.Add("QRCodeImgUrl", typeof(string));
string info = string.Empty;
var path1 = "D:\\BaiduNetdiskDownload\\web\\webAgent";// System.AppDomain.CurrentDomain.BaseDirectory;//获取程序集目录
//string path = Path.Combine(path1, "images", "QRCode");//Path.Combine 将3个字符串组合成路径
string path = ApplicationSettings.Get("QRCodeUrl");
var images = Directory.GetFiles(path, ".", SearchOption.AllDirectories);
//images = Directory.GetFiles(path, "*.png|*.jpg", SearchOption.AllDirectories);
//Directory.GetFiles 返回指定目录的文件路径 SearchOption.AllDirectories 指定搜索当前目录及子目录
//遍历string 型 images数组
foreach (var i in images)
{
//图片名称
var str1 = i.Replace(path, "");//获取相对路径
var QRCodeName = str1.Replace("\\", "/");//将字符“\\”转换为“/”
//图片地址
var str2 = i.Replace(path1, "");
var QRCodeUrl = str2.Replace("\\", "/");
//图片真实地址
var str3 = "http://47.105.214.34:85" + QRCodeUrl;
var QRCodeImgUrl = str3.Replace("\\", "/");
DataRow dr = dt.NewRow();
dr[0] = QRCodeName; //通过索引赋值
dr[1] = QRCodeUrl;
dr[2] = QRCodeImgUrl;
dt.Rows.Add(dr);
}
return Json(new
{
IsOk = true,
Total = dt.Rows.Count,
Data = JsonHelper.SerializeObject(dt)
});
}
catch (Exception ex)
{
return Json(new
{
IsOk = false,
Msg = ex.Message
});
}
}
///
/// 删除二维码
///
///
[AntiSqlInjection]
[CheckCustomer]
public JsonResult DeletePayQRCode()
{
if (user != null)
{
AdminPermission adminPermission = new AdminPermission(user, user.MoudleID);
if (!adminPermission.GetPermission(8L))
{
return Json(new
{
IsOk = false,
Msg = "没有权限",
Url = "/NoPower/Index"
});
}
}
string text = TypeUtil.ObjectToString(base.Request["cid"]);
if (!string.IsNullOrEmpty(text))
{
string path = ApplicationSettings.Get("QRCodeUrl");
path = path + text;
var fileUrl = path.Replace("\\", "/");
try
{
System.IO.File.Delete(path);
//string file =System.Web.HttpContext.Current.Server.MapPath(fileUrl);
//if (System.IO.File.Exists(file))
//{
// System.IO.File.Delete(file);
//}
return Json(new
{
IsOk = true,
Msg = "删除成功"
});
}
catch
{
return Json(new
{
IsOk = false,
Msg = "删除失败"
});
}
}
return Json(new
{
IsOk = false,
Msg = "没有删除的项"
});
}
///
/// 添加二维码
///
///
[CheckCustomer]
public ActionResult AddPayQRCode()
{
return View();
}
///
/// 上传图片到服务器
///
///
[HttpPost]
public string UploadFileToLocal()
{
APIResult aPIResult = new APIResult();
try
{
int num = TypeUtil.ObjectToInt(base.Request["op"]);
int num2 = 0;
if (num > 0)
{
EnumerationList.UploadFileEnum uploadFileEnum = (EnumerationList.UploadFileEnum)Enum.Parse(typeof(EnumerationList.UploadFileEnum), num.ToString());
string text = "";
switch (uploadFileEnum)
{
case EnumerationList.UploadFileEnum.PayQRCode:
num2 = 0;
text = "/images/QRCode/";
break;
}
HttpPostedFileBase httpPostedFileBase = base.Request.Files[0];
if (!string.IsNullOrEmpty(text))
{
string text2 = ApplicationSettings.Get("QRCodeUrl");
string str = "";
bool flag = true;
if (num2 == 0)
{
if (!ValidateHelper.IsImgFileName(httpPostedFileBase.FileName))
{
flag = false;
aPIResult.error = -2;
aPIResult.msg = "上传文件的格式不对!";
}
if (httpPostedFileBase.ContentLength >= 2097152)
{
aPIResult.error = -2;
aPIResult.msg = "上传文件的大小不能大于2M!";
flag = false;
}
str = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
text2 += str;
}
if (flag)
{
string path = text2.Substring(0, text2.LastIndexOf("\\"));
DirectoryInfo directoryInfo = new DirectoryInfo(path);
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.Write);
byte[] @byte = TypeUtil.GetByte(httpPostedFileBase.InputStream);
fileStream.Write(@byte, 0, @byte.Length);
fileStream.Flush();
fileStream.Close();
aPIResult.error = -2;
aPIResult.msg = "上传成功";
aPIResult.url = text + str;
}
}
else
{
aPIResult.error = -1;
aPIResult.msg = "路径出错";
}
}
else
{
aPIResult.error = -2;
aPIResult.msg = "op出错";
}
}
catch (Exception ex)
{
aPIResult.error = -2;
aPIResult.msg = "上传图片异常";
LogUtil.WriteError(ex.ToString());
}
return JsonConvert.SerializeObject(aPIResult);
}
#endregion