学习笔记13 独立出discuz 论坛中的图片上传

最近2天都在搞图片上传这个东西,真是有点麻烦。

在discuz 源码中看到一图片上传的好东西,刚好可以用到项目中来。于是决定尝试下把论坛中的图片上传独立出来

黄天不负有心人。就在刚才我把它搞出来了,而且通过了测试。

先将独立出来的部分发于博客中:

通过我的观察 发现原来论坛中的flash上传图片是有三个部分组成。一是前台的js文件 二是flash中的as文件 三是asp.net中的代码处理

原理是这样的:

根据不同的浏览器js 加载flash文件和对于的参数【这个参数是页面传入的】 到flash中处理文件【这是第一步的处理,只是将图片路径和用户信息传入到-->asp.net类中】这样asp。net类中就可以得到图片路径和用户信息,在得到用户信息以后,程序判断用户是否存在,是否有权限这样做。当后台验证通过了。就上传一个临时的图片文件到项目中并且return出去。 flash得到这个返回值 判断临时图片是否上传成功了,如果成功,将图片显示出来并且可以用于截图使用,这样可以截取的图片就出来了。 下面的操作就是用户选择大小 选择截图的位置。点击确定。这个时候flash就第二次访问asp。net中的类【这是第二次的处理,将临时文件delete将用户截取的图片上传到正式的图片中去】 当asp。net中的类处理操作完成了return true。这样页面上传图片就算是成功了。

原理我明白以后 下面要做的就是将这些我需要的文件搞出来,不要的果断就抛下了

前台的js 我的项目中就可以直接的使用静态的了

写法是:

注意:ucapi=http://192.168.0.101/ajaxpage.aspx\" 这是一个参数 用处是:flash和哪一个asp.net的类联系。 这个参数必不可少,而且必须用绝对路径,不然是要报错的。

var HeadPic="<%=HeadPic %>";//这是显示原来用户上传的图片的一个变量
var ManID="<%=ManID%>"//这是用户的id
jQuery(function(){
jQuery("#ShowPic").html("<img src='"+HeadPic+"'/>");//显示用户当前头像
if (BROWSER.ie){//判断浏览器是否是ie的
jQuery("#pictd").html("<object name=\"mycamera\" width=\"540\" height=\"253\" id=\"mycamera\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\"><PARAM NAME=\"_cx\" VALUE=\"14287\"><PARAM NAME=\"_cy\" VALUE=\"6693\"><PARAM NAME=\"FlashVars\" VALUE=\"\"><PARAM NAME=\"Movie\" VALUE=\" ../images/common/camera.swf?nt=1&amp;inajax=1&amp;appid=5d45677bdfb5e56996e632f1b04df21b&amp;input=QMPeW2gQeHU=&amp;MainID="+ManID+"&amp;ucapi=http://192.168.0.101/ajaxpage.aspx\"><PARAM NAME=\"Src\" VALUE=\" ../images/common/camera.swf?nt=1&amp;inajax=1&amp;appid=5d45677bdfb5e56996e632f1b04df21b&amp;input=QMPeW2gQeHU=&amp;MainID="+ManID+"&amp;ucapi=http://192.168.0.101/ajaxpage.aspx\"><PARAM NAME=\"WMode\" VALUE=\"Transparent\"><PARAM NAME=\"Play\" VALUE=\"0\"><PARAM NAME=\"Loop\" VALUE=\"-1\"><PARAM NAME=\"Quality\" VALUE=\"High\"><PARAM NAME=\"SAlign\" VALUE=\"\"><PARAM NAME=\"Menu\" VALUE=\"0\"><PARAM NAME=\"Base\" VALUE=\"\"><PARAM NAME=\"AllowScriptAccess\" VALUE=\"always\"><PARAM NAME=\"Scale\" VALUE=\"NoScale\"><PARAM NAME=\"DeviceFont\" VALUE=\"0\"><PARAM NAME=\"EmbedMovie\" VALUE=\"0\"><PARAM NAME=\"BGColor\" VALUE=\"FFFFFF\"><PARAM NAME=\"SWRemote\" VALUE=\"\"><PARAM NAME=\"MovieData\" VALUE=\"\"><PARAM NAME=\"SeamlessTabbing\" VALUE=\"1\"><PARAM NAME=\"Profile\" VALUE=\"0\"><PARAM NAME=\"ProfileAddress\" VALUE=\"\"><PARAM NAME=\"ProfilePort\" VALUE=\"0\"><PARAM NAME=\"AllowNetworking\" VALUE=\"all\"><PARAM NAME=\"AllowFullScreen\" VALUE=\"false\"></object>");
}else{//不是ie的 使用下面的加载方法
jQuery("#pictd").html("<embed height=\"253\" width=\"540\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" swliveconnect=\"true\" menu=\"false\" wmode=\"transparent\" bgcolor=\"#ffffff\" quality=\"high\" name=\"mycamera\" src=\"../images/common/camera.swf?nt=1&amp;inajax=1&amp;appid=2480130ef6144ee4ec7b8bb6ee818178&amp;input=7EyPXS2l2uo=&amp;MainID="+ManID+"&amp;ucapi=http://192.168.0.101/ajaxpage.aspx\" scale=\"exactfit\">")
}
});


通过上面的方法 如果js没错的话 应该在页面上看到:这样的效果。

下一步就对ajaxpage页面做修改。

原来的页面情况是:在flash中指定的是ajax.aspx页面 而ajax页面中将处理的内容是放到一个类中的,当然我们完全可以不用它这种方式 直接新建一个页面--》ajaxPage页面就行了。

页面代码和药修改的地方:

可以看到这个类少了很多 以前的东西,以为我们不必要处理那么多的事件,只是一个单纯的上传图片的处理而已。

主要要修改的地方:是上传图片的路径【一个是临时文件,第二个是保持的文件路径】。

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Common;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;


using Discuz.Common;
using Discuz.Forum;
using Discuz.Entity;
using Discuz.Cache;
using Discuz.Config;
using Discuz.Plugin.Space;
using Discuz.Plugin.Album;
using Discuz.Plugin.Mall;
using Discuz.Common.Generic;
using Newtonsoft.Json;


public partial class ajaxPage : System.Web.UI.Page
{


string uId = "";
string corpId = "";
GeneralConfigInfo config;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UMID"] != null)//如果session中是有值的
{
corpId = Session["UMID"].ToString().Split('|')[0];//商家id
uId = Session["UMID"].ToString().Split('|')[1];//用户id
}
//uid = DNTRequest.GetString("MainID");
string type = DNTRequest.GetString("t");
if (DNTRequest.GetString("Filename") != "" && DNTRequest.GetString("Upload") != "")
{


ResponseText(UploadTempAvatar(uId));
return;
}
if (DNTRequest.GetString("avatar1") != "" && DNTRequest.GetString("avatar2") != "" && DNTRequest.GetString("avatar3") != "")
{
CreateDir(uId);
if (!(SaveAvatar("avatar1", uId) && SaveAvatar("avatar2", uId) && SaveAvatar("avatar3", uId)))
{
File.Delete(Utils.GetMapPath("images\\temp\\avatar_" + uId + ".jpg"));
ResponseText("<?xml version=\"1.0\" ?><root><face success=\"0\"/></root>");
return;
}
File.Delete(Utils.GetMapPath("images\\temp\\avatar_" + uId + ".jpg"));
ResponseText("<?xml version=\"1.0\" ?><root><face success=\"1\"/></root>");
return;
}
}
#region 头像
/// <summary>
/// 解码Uid
/// </summary>
/// <param name="encodeUid"></param>
/// <returns></returns>
private string DecodeUid(string encodeUid)
{
return "1";
}


/// <summary>
/// 获取游客的所在地
/// </summary>
private void GetIpList()
{
try
{
string[] ipList = Utils.SplitString(DNTRequest.GetString("iplist"), ",");
string[] pidList = Utils.SplitString(DNTRequest.GetString("pidlist"), ",");
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < ipList.Length; i++)
{
sb.Append("'");
sb.Append(pidList[i]);
sb.Append("|");
sb.Append(IpSearch.GetAddressWithIP(ipList[i].Replace("*", "1")));
sb.Append("'");
sb.Append(",");
}
ResponseJSON(sb.ToString().TrimEnd(',') + "]");
}
catch //添加try语法, 以防止在并发情况下, 服务器端远程链接被关闭后出现应用程序 '警告'(事件查看器)
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Expires = 0;
System.Web.HttpContext.Current.Response.Cache.SetNoStore();
System.Web.HttpContext.Current.Response.End();
}
}


/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="uid"></param>
private void CreateDir(string uid)
{
string avatarDir = string.Format("images/{0}",
corpId);
if (!Directory.Exists(Utils.GetMapPath(avatarDir)))
Directory.CreateDirectory(Utils.GetMapPath(avatarDir));
}


/// <summary>
/// 保存头像文件
/// </summary>
/// <param name="avatar"></param>
/// <param name="uid"></param>
/// <returns></returns>
private bool SaveAvatar(string avatar, string uid)
{
byte[] b = FlashDataDecode(DNTRequest.GetString(avatar));
if (b.Length == 0)
return false;
string size = "";
if (avatar == "avatar1")
size = "large";
else if (avatar == "avatar2")
size = "medium";
else
size = "small";
string avatarFileName = string.Format("images/{0}/{1}{2}_headpic.jpg",
corpId, uid, size);
FileStream fs = new FileStream(Utils.GetMapPath(avatarFileName), FileMode.Create);
fs.Write(b, 0, b.Length);
fs.Close();
return true;
}


/// <summary>
/// 解码Flash头像传送的数据
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private byte[] FlashDataDecode(string s)
{
byte[] r = new byte[s.Length / 2];
int l = s.Length;
for (int i = 0; i < l; i = i + 2)
{
int k1 = ((int)s[i]) - 48;
k1 -= k1 > 9 ? 7 : 0;
int k2 = ((int)s[i + 1]) - 48;
k2 -= k2 > 9 ? 7 : 0;
r[i / 2] = (byte)(k1 << 4 | k2);
}
return r;
}


/// <summary>
/// 上传临时头像文件
/// </summary>
/// <returns></returns>
private string UploadTempAvatar(string uid)
{
string filename = "avatar_" + uid + ".jpg";
string uploadUrl = "images/";
string uploadDir = Utils.GetMapPath("images\\");
if (!Directory.Exists(uploadDir + "temp\\"))
Utils.CreateDir(uploadDir + "temp\\");
filename = "temp/" + filename;
HttpContext.Current.Request.Files[0].SaveAs(uploadDir + filename);
return "http://192.168.0.101/" + uploadUrl + filename;
}
#endregion




//private void GetAjaxForumsJsonList()
//{
// StringBuilder sb = new StringBuilder();
// List<ForumInfo> forumlist = Forums.GetSubForumList(DNTRequest.GetInt("fid", 0));
// sb.Append("[");
// if (forumlist != null && forumlist.Count > 0)
// {
// foreach (ForumInfo info in forumlist)
// {
// if (config.Hideprivate == 1 && info.Viewperm != "" && !Utils.InArray(usergroupid.ToString(), info.Viewperm))
// continue;
// sb.Append(string.Format("{{'forumname':'{0}','fid':{1},'parentid':{2},'applytopictype':{3},'topictypeselectoptions':'{4}','postbytopictype':{5}}},", info.Name.Trim(), info.Fid.ToString(), info.Parentid.ToString(), info.Applytopictype.ToString(), Forums.GetCurrentTopicTypesOption(info.Fid, info.Topictypes), info.Postbytopictype.ToString()));
// }
// if (sb.ToString() != "")
// ResponseJSON(sb.ToString().Remove(sb.ToString().Length - 1) + "]");
// }
// ResponseJSON(sb.Append("]").ToString());
//}


private void GetPostInfo()
{
PostInfo info = Posts.GetPostInfo(DNTRequest.GetInt("tid", 0), Posts.GetTopicPostInfo(DNTRequest.GetInt("tid", 0)).Pid);
StringBuilder xmlnode = IsValidGetPostInfo(info);
if (!xmlnode.ToString().Contains("<error>"))
{
xmlnode.Append("<post>\r\n\t");
xmlnode.AppendFormat("<message>{0}</message>\r\n", info.Message);
xmlnode.AppendFormat("<tid>{0}</tid>\r\n", info.Tid);
xmlnode.Append("</post>\r\n\t");
}
ResponseXML(xmlnode);
}


private StringBuilder IsValidGetPostInfo(PostInfo info)
{
StringBuilder xmlnode = new StringBuilder();
xmlnode.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
if (!DNTRequest.IsPost() || ForumUtils.IsCrossSitePost())
{
xmlnode.Append("<error>您的请求来路不正确,无法提交。如果您安装了某种默认屏蔽来路信息的个人防火墙软件(如 Norton Internet Security),请设置其不要禁止来路信息后再试。</error>");
return xmlnode;
}
if (info == null)
{
xmlnode.Append("<error>读取帖子失败</error>");
return xmlnode;
}
return xmlnode;
}


private void ResponseText(string text)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(text);
HttpContext.Current.Response.End();
}


private void ResponseText(StringBuilder builder)
{
ResponseText(builder.ToString());
}


private string ValidatePurview()
{
return string.Empty;
}


private void GetForumTopicTypeList()
{
int fid = DNTRequest.GetInt("fid", 0);
if (fid <= 0)
ResponseText("[]");


ForumInfo forumInfo = Forums.GetForumInfo(fid);
if (forumInfo == null)
ResponseText("[]");
if (string.IsNullOrEmpty(forumInfo.Topictypes))
ResponseText("[]");


StringBuilder sb = new StringBuilder("[{'typeid':'0','typename':'分类'}");


foreach (string topictype in forumInfo.Topictypes.Split('|'))
{
if (!Utils.StrIsNullOrEmpty(topictype.Trim()))
{
sb.Append(",{");
sb.AppendFormat("'typeid':'{0}','typename':'{1}'", topictype.Split(',')[0], topictype.Split(',')[1]);
sb.Append("}");
}
}
sb.Append("]");


ResponseText(sb);
}




/// <summary>
/// 获取图片标签
/// </summary>
private void GetPhotoTags()
{
if (!DNTRequest.IsPost() || ForumUtils.IsCrossSitePost())
{
Response.Write("您的请求来路不正确,无法提交。如果您安装了某种默认屏蔽来路信息的个人防火墙软件(如 Norton Internet Security),请设置其不要禁止来路信息后再试。");
return;
}
if (DNTRequest.GetInt("photoid", 0) <= 0) return;


string filename = Utils.GetMapPath(string.Format("{0}cache/photo/{1}/{2}_tags.txt", BaseConfigs.GetForumPath, DNTRequest.GetInt("photoid", 0) / 1000 + 1, DNTRequest.GetInt("photoid", 0)));
if (!File.Exists(filename))
AlbumPluginProvider.GetInstance().WritePhotoTagsCacheFile(DNTRequest.GetInt("photoid", 0));


WriteFile(filename);
}


/// <summary>
/// 获取指定路径下的文件内容并输出
/// </summary>
/// <param name="filename">文件所在路径</param>
private void WriteFile(string filename)
{
string tags = "";


if (File.Exists(filename))
{
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
tags = sr.ReadToEnd();
}
}
}


HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(tags);
HttpContext.Current.ApplicationInstance.CompleteRequest();
//HttpContext.Current.Response.End();
}


/// <summary>
/// 获取图片热门标签
/// </summary>
private void GetPhotoHotTags()
{
string filename = Utils.GetMapPath(BaseConfigs.GetForumPath + AlbumPluginProvider.GetInstance().PHOTO_HOT_TAG_CACHE_FILENAME);
if (!File.Exists(filename))
AlbumPluginProvider.GetInstance().WriteHotTagsListForPhotoJSONPCacheFile(60);


WriteFile(filename);
}


/// <summary>
/// 获取空间热门标签
/// </summary>
private void GetSpaceHotTags()
{
string filename = Utils.GetMapPath(BaseConfigs.GetForumPath + SpacePluginProvider.GetInstance().SpaceHotTagJSONPCacheFileName);
if (!File.Exists(filename))
SpacePluginProvider.GetInstance().WriteHotTagsListForSpaceJSONPCacheFile(60);


WriteFile(filename);
}


/// <summary>
/// 获取论坛热门标签
/// </summary>
private void GetForumHotTags()
{
string filename = Utils.GetMapPath(BaseConfigs.GetForumPath + ForumTags.ForumHotTagJSONPCacheFileName);
if (!File.Exists(filename))
ForumTags.WriteHotTagsListForForumJSONPCacheFile(60);


WriteFile(filename);
}




/// <summary>
/// 空间日志标签缓存文件
/// </summary>
private void GetSpacePostTags()
{
SpacePluginProvider.GetInstance().GetSpacePostTagsCacheFile(DNTRequest.GetInt("postid", 0));
}






/// <summary>
/// 获取根据Tag的相关主题
/// </summary>
private void GetTopicsWithSameTag()
{
if (DNTRequest.GetInt("tagid", 0) > 0)
{
TagInfo tag = Tags.GetTagInfo(DNTRequest.GetInt("tagid", 0));
if (tag != null)
{
List<TopicInfo> topics = Topics.GetTopicsWithSameTag(DNTRequest.GetInt("tagid", 0), config.Tpp);
StringBuilder builder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
builder.Append("<root><![CDATA[ \r\n");
builder.Append(@"<div class=""tagthread"" style=""width:300px"">
<a class=""close"" href=""javascript:;hideMenu()"" title=""关闭""><img src=""images/common/close.gif"" alt=""关闭"" /></a>
<h4>标签: ");
builder.Append(string.Format("<font color='{1}'>{0}</font>", tag.Tagname, tag.Color));
builder.Append("</h4>\r\n<ul>\r\n");
foreach (TopicInfo topic in topics)
{
builder.Append(string.Format(@"<li><a href=""{0}"" target=""_blank"">{1}</a></li>", Urls.ShowTopicAspxRewrite(topic.Tid, 1), topic.Title));
}
builder.Append(string.Format(@"<li class=""more""><a href=""tags.aspx?tagid={0}"" target=""_blank"">查看更多</a></li>", tag.Tagid));
builder.Append("</ul>\r\n");
builder.Append(@"</div>
]]></root>");


ResponseXML(builder);
}
}
}


/// <summary>
/// 读取主题标签缓存文件
/// </summary>
private void GetTopicTags()
{
if (DNTRequest.GetInt("topicid", 0) > 0)
{
StringBuilder dir = new StringBuilder();
dir.Append(BaseConfigs.GetForumPath);
dir.Append("cache/topic/magic/");
dir.Append((DNTRequest.GetInt("topicid", 0) / 1000 + 1).ToString());
dir.Append("/");
string filename = Utils.GetMapPath(dir.ToString() + DNTRequest.GetInt("topicid", 0) + "_tags.config");
if (!File.Exists(filename))
{
ForumTags.WriteTopicTagsCacheFile(DNTRequest.GetInt("topicid", 0));
}


WriteFile(filename);
}
}


/// <summary>
/// 获取关键字分词
/// </summary>
private void GetRelateKeyword()
{
string title = Utils.UrlEncode(Utils.RemoveHtml(Utils.ClearUBB(DNTRequest.GetString("titleenc").Trim())));
string content = Utils.RemoveHtml(Utils.ClearUBB(DNTRequest.GetString("contentenc").Trim()));
content = content.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
content = Utils.GetUnicodeSubString(content, 500, string.Empty);
content = Utils.UrlEncode(content);


string xmlContent = Utils.GetSourceTextByUrl(string.Format("http://keyword.discuz.com/related_kw.html?title={0}&content={1}&ics=utf-8&ocs=utf-8", title, content));


XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlContent);


XmlNodeList xnl = xmldoc.GetElementsByTagName("kw");
StringBuilder builder = new StringBuilder();
foreach (XmlNode node in xnl)
{
builder.AppendFormat("{0} ", node.InnerText);
}


StringBuilder xmlBuilder = new StringBuilder(string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
<root><![CDATA[
<script type=""text/javascript"">
var tagsplit = $('tags').value.split(' ');
var inssplit = '{0}';
var returnsplit = inssplit.split(' ');
var result = '';
for(i in tagsplit) {{
for(j in returnsplit) {{
if(tagsplit[i] == returnsplit[j]) {{
tagsplit[i] = '';break;
}}
}}
}}


for(i in tagsplit) {{
if(tagsplit[i] != '') {{
result += tagsplit[i] + ' ';
}}
}}
$('tags').value = result + '{0}';
</script>
]]></root>", builder.ToString()));


ResponseXML(xmlBuilder);
}


/// <summary>
/// 输出表情字符串
/// </summary>
private void GetSmilies()
{
//如果不是提交...
if (ForumUtils.IsCrossSitePost()) return;


HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write("{" + Caches.GetSmiliesCache() + "}");
HttpContext.Current.ApplicationInstance.CompleteRequest();
//HttpContext.Current.Response.End();
}


/// <summary>
/// 检查Rewritename是否存在
/// </summary>
private void CheckRewriteName()
{
//if (userid == -1) return;


System.Text.StringBuilder xmlnode = new System.Text.StringBuilder();


xmlnode.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xmlnode.Append("<result>");
xmlnode.Append(SpacePluginProvider.GetInstance().CheckSpaceRewriteNameAvailable(DNTRequest.GetString("rewritename").Trim()).ToString());
xmlnode.Append("</result>");
ResponseXML(xmlnode);
}


/// <summary>
/// 查询用户名是否存在
/// </summary>
public void CheckUserName()
{
if (DNTRequest.GetString("username").Trim() == "")
return;
string result = "0";
string tmpUsername = DNTRequest.GetString("username").Trim();
if (tmpUsername.IndexOf(" ") != -1)//用户名中不允许包含全空格符
result = "1";
else if (tmpUsername.IndexOf(" ") != -1) //用户名中不允许包含空格
result = "1";
else if (tmpUsername.IndexOf(":") != -1) //用户名中不允许包含冒号
result = "1";
else if (Users.GetUserId(tmpUsername) > 0) //该用户名已存在
result = "1";
else if ((!Utils.IsSafeSqlString(tmpUsername)) || (!Utils.IsSafeUserInfoString(tmpUsername))) //用户名中存在非法字符
result = "1";
else if (tmpUsername.Trim() == PrivateMessages.SystemUserName || ForumUtils.IsBanUsername(tmpUsername, config.Censoruser)) //如果用户名属于禁止名单, 或者与负责发送新用户注册欢迎信件的用户名称相同
result = "1";


System.Text.StringBuilder xmlnode = new System.Text.StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
ResponseXML(xmlnode.AppendFormat("<result>{0}</result>", result));
}


/// <summary>
/// 获得帖子评分列表
/// </summary>
public void GetRateLogList()
{
System.Text.StringBuilder xmlnode = new System.Text.StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");


//如果不是提交...
if (!DNTRequest.IsPost() || ForumUtils.IsCrossSitePost())
{
xmlnode.Append("<error>您的请求来路不正确,无法提交。如果您安装了某种默认屏蔽来路信息的个人防火墙软件(如 Norton Internet Security),请设置其不要禁止来路信息后再试。</error>");
ResponseXML(xmlnode);
return;
}


try
{
List<RateLogInfo> rateList = Posts.GetPostRateLogList(DNTRequest.GetFormInt("pid", 0));
if (rateList == null || rateList.Count == 0)
{
xmlnode.Append("<error>该帖没有评分记录</error>");
ResponseXML(xmlnode);
return;
}
xmlnode.Append("<data>\r\n");


List<RateLogInfo> finalRateList = new List<RateLogInfo>();


//该循环用于将评分列表中多次评分用户的分值聚合成一条数据
foreach (RateLogInfo info in rateList)
{
Predicate<RateLogInfo> match = new Predicate<RateLogInfo>(delegate(RateLogInfo rateLog) { return rateLog.Uid == info.Uid && rateLog.ExtCredits == info.ExtCredits; });
RateLogInfo finalRateInfo = finalRateList.Find(match);
if (finalRateInfo == null)
finalRateList.Add(info);
else
{
finalRateInfo.Score += info.Score;
finalRateInfo.Reason = string.IsNullOrEmpty(finalRateInfo.Reason) ? info.Reason : finalRateInfo.Reason;
}
}


string[] scorename = Scoresets.GetValidScoreName();
string[] scoreunit = Scoresets.GetValidScoreUnit();


int uidCount = 0;
int previoursUid = 0;
foreach (RateLogInfo rate in finalRateList)
{
if (previoursUid != rate.Uid)
uidCount++;
xmlnode.Append("<ratelog>");
xmlnode.AppendFormat("\r\n\t<rateid>{0}</rateid>", rate.Id);
xmlnode.AppendFormat("\r\n\t<uid>{0}</uid>", rate.Uid);
xmlnode.AppendFormat("\r\n\t<username>{0}</username>", rate.UserName.Trim());
xmlnode.AppendFormat("\r\n\t<extcredits>{0}</extcredits>", rate.ExtCredits);
xmlnode.AppendFormat("\r\n\t<extcreditsname>{0}</extcreditsname>", scorename[rate.ExtCredits]);
xmlnode.AppendFormat("\r\n\t<extcreditsunit>{0}</extcreditsunit>", scoreunit[rate.ExtCredits]);
xmlnode.AppendFormat("\r\n\t<postdatetime>{0}</postdatetime>", ForumUtils.ConvertDateTime(rate.PostDateTime));
xmlnode.AppendFormat("\r\n\t<score>{0}</score>", rate.Score > 0 ? ("+" + rate.Score.ToString()) : rate.Score.ToString());
xmlnode.AppendFormat("\r\n\t<reason>{0}</reason>", rate.Reason.Trim());
xmlnode.Append("\r\n</ratelog>\r\n");
previoursUid = rate.Uid;
}
xmlnode.Append("</data>");


ResponseXML(xmlnode);
if (DNTRequest.GetFormInt("ratetimes", 0) != uidCount)
Posts.UpdatePostRateTimes(DNTRequest.GetFormInt("tid", 0), DNTRequest.GetFormInt("pid", 0).ToString());
}
catch //添加try语法, 以防止在并发情况下, 服务器端远程链接被关闭后出现应用程序 '警告'(事件查看器)
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Expires = 0;
System.Web.HttpContext.Current.Response.Cache.SetNoStore();
System.Web.HttpContext.Current.Response.End();
}
}


/// <summary>
/// 获取相册导航
/// </summary>
public void GetAlbum()
{
//如果不是提交...
if (ForumUtils.IsCrossSitePost())
return;


if (DNTRequest.GetQueryInt("albumid", 0) < 1)
return;


AlbumPluginProvider.GetInstance().CreateAlbumJsonData(DNTRequest.GetQueryInt("albumid", 0));
string builder = AlbumPluginProvider.GetInstance().GetAlbumJsonData(DNTRequest.GetQueryInt("albumid", 0));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(builder);
HttpContext.Current.Response.End();
}


/// <summary>
/// 通过留言id获取留言信息
/// </summary>
/// <param name="leavewordid">留言id</param>
private void GetGoodsLeaveWordById(int leavewordid)
{
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(MallPluginProvider.GetInstance().GetLeaveWordJson(leavewordid));
HttpContext.Current.Response.End();
}


/// <summary>
/// 获取指定商品下的留言
/// </summary>
/// <param name="goodsid">商品id</param>
/// <param name="pagesize">页面大小</param>
/// <param name="pageindex">当前页</param>
private void GetGoodsLeaveWord(int goodsid, int pagesize, int pageindex)
{
pageindex = (pageindex < 0) ? 1 : pageindex;
pagesize = (pagesize < 0 || pagesize > 25) ? 25 : pagesize;


HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(MallPluginProvider.GetInstance().GetLeaveWordJson(goodsid, pagesize, pageindex, "id", 0).ToString());
HttpContext.Current.Response.End();
}


/// <summary>
/// 获取交易日志
/// </summary>
/// <param name="goodsid">商品id</param>
/// <param name="pagesize">页面大小</param>
/// <param name="pageindex">当前页</param>
/// <param name="orderby">排序字段</param>
/// <param name="ascdesc">排序方法</param>
private void GetGoodsTradeLog(int goodsid, int pagesize, int pageindex, string orderby, int ascdesc)
{
pageindex = (pageindex < 0) ? 1 : pageindex;
pagesize = (pagesize < 0 || pagesize > 25) ? 25 : pagesize;


HttpContext.Current.Response.Clear();
if (Utils.InArray(orderby, "lastupdate"))
HttpContext.Current.Response.Write(MallPluginProvider.GetInstance().GetTradeLogJson(goodsid, pagesize, pageindex, orderby, ascdesc).ToString());


HttpContext.Current.Response.End();
}


/// <summary>
/// 获取指定用户id的商品评价(信用)
/// </summary>
/// <param name="uid">用户id</param>
/// <param name="uidtype">用户类型(1:卖方 2:买方)</param>
/// <param name="ratetype">评价类型(1:好评 2:中评 3:差评)</param>
/// <param name="filter">过滤方式(或字段)</param>
private void GetGoodsRatesList(int uid, int uidtype, int ratetype, string filter)
{
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(MallPluginProvider.GetInstance().GetGoodsRatesJson(uid, uidtype, ratetype, filter));
HttpContext.Current.Response.End();
}


/// <summary>
/// 获取论坛热门标签
/// </summary>
private void GetMallHotTags()
{
string filename = Utils.GetMapPath(BaseConfigs.GetForumPath + MallPluginBase.GoodsHotTagJSONPCacheFileName);
if (!File.Exists(filename))
MallPluginProvider.GetInstance().WriteHotTagsListForGoodsJSONPCacheFile(60);


WriteFile(filename);
}


/// <summary>
/// 获取热门商品信息
/// </summary>
/// <param name="days">天数</param>
/// <param name="categroyid">商品分类</param>
/// <param name="count">返回记录条数</param>
private void GetHotGoods(int days, int categroyid, int count)
{
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(MallPluginProvider.GetInstance().GetHotGoodsJsonData(days, categroyid, count));
HttpContext.Current.Response.End();
}


/// <summary>
/// 获取热门或新开的店铺信息
/// </summary>
/// <param name="shoptype">热门店铺(1:热门店铺, 2 :新开店铺)</param>
/// <returns></returns>
private void GetShopInfoJson(int shoptype)
{
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(MallPluginProvider.GetInstance().GetShopInfoJson(shoptype));
HttpContext.Current.Response.End();
}




private void GetGoodsList(int categroyid, int order, int topnumber)
{
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(MallPluginProvider.GetInstance().GetGoodsListJsonData(categroyid, order, topnumber));
HttpContext.Current.Response.End();
}




private void Getdebatesjsonlist(string callback, string tidllist)
{
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(Debates.GetDebatesJsonList(callback, tidllist));
HttpContext.Current.Response.End();
}


/// <summary>
/// 获取指定符件id的附件交易日志
/// </summary>
/// <param name="aId">指定的附件id</param>
private void GetAttachPaymentLogByAid(int aid)
{
if (aid > 0)
{
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(AttachPaymentLogs.GetAttachPaymentLogJsonByAid(aid));
HttpContext.Current.Response.End();
}
}


/// <summary>
/// 图片缓存方法
/// </summary>
private void GetImage()
{
//检查参数是否合法
if (DNTRequest.GetString("aid") == "" || DNTRequest.GetString("size") == "" || DNTRequest.GetString("key") == "")
{
HttpContext.Current.Response.Redirect("images/common/none.gif");
return;
}
string forumPath = BaseConfigs.GetBaseConfig().Forumpath;
//是否在服务器上缓存图片
bool nocache = DNTRequest.GetString("nocache") == "yes";
int aid = DNTRequest.GetInt("aid", 0);
//缩略图缩略方式
string type = DNTRequest.GetString("type") != "" ? DNTRequest.GetString("type") : "fixwr";
string[] wxh = DNTRequest.GetString("size").Split('x');
//宽
int w = TypeConverter.StrToInt(wxh[0]);
//高
int h = TypeConverter.StrToInt(wxh[1]);
string thumbfile = string.Format("{0}_{1}_{2}.jpg'", aid, w, h);
string attachurl = forumPath + "cache/thumbnail/";
//获取缓存图片
if (!nocache)
{
if (File.Exists(Utils.GetMapPath(attachurl + thumbfile)))
{
HttpContext.Current.Response.Redirect(attachurl + thumbfile);
return;
}
}
//校验参数正确性
string hash = Discuz.Common.DES.Encode(aid.ToString() + "," + w.ToString() + "," + h.ToString(), Utils.MD5(aid.ToString())).Replace("+", "[");
if (hash != DNTRequest.GetString("key"))
{
HttpContext.Current.Response.Redirect("images/common/none.gif");
return;
}
AttachmentInfo attInfo = Attachments.GetAttachmentInfo(aid);
//客户端缓存60分,在firefox下调试状态失效
HttpContext.Current.Response.Expires = 60;
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddMinutes(60);


if (!Directory.Exists(Utils.GetMapPath(attachurl)))
Directory.CreateDirectory(Utils.GetMapPath(attachurl));
//生成缩略图
if (attInfo.Filename.StartsWith("http://")) //远程附件
{
Thumbnail.MakeRemoteThumbnailImage(attInfo.Filename, Utils.GetMapPath(attachurl + thumbfile), w, h);
}
else
Thumbnail.MakeThumbnailImage(Utils.GetMapPath(forumPath + "images/" + attInfo.Filename), Utils.GetMapPath(attachurl + thumbfile), w, h);
if (nocache)
{
HttpContext.Current.Response.ContentType = "image/jpg";
HttpContext.Current.Response.BinaryWrite(File.ReadAllBytes(Utils.GetMapPath(attachurl + thumbfile)));
try
{
File.Delete(Utils.GetMapPath(attachurl + thumbfile));
}
catch { }
}
else
{
HttpContext.Current.Response.Redirect(attachurl + thumbfile);
}
}


private void ResetEmail()
{
int uid = DNTRequest.GetInt("uid", -1);
if (uid <= 0)
{
ResponseText("{'text':'非法请求','code':0}");
return;
}


string newEmail = DNTRequest.GetString("newemail");
if (!Utils.IsValidEmail(newEmail))
{
ResponseText("{'text':'E-mail格式不正确','code':0}");
return;
}


UserInfo userInfo = Users.GetUserInfo(uid);
if (Utils.MD5(string.Concat(userInfo.Password, config.Passwordkey, DNTRequest.GetString("ts"))) != DNTRequest.GetString("auth"))
{
ResponseText("{'text':'非法请求','code':0}");
return;
}


//如果接收到的时间戳是在两分钟之前的,则证明该操作已经超过了操作时限
if (long.Parse(DNTRequest.GetString("ts")) < DateTime.Now.AddMinutes(-2).Ticks)
{
ResponseText("{'text':'该操作已经超过了时限,无法执行','code':0}");
return;
}


if (userInfo.Groupid != 8)
{
ResponseText("{'text':'该用户不是等待验证的用户','code':0}");
return;
}
if (userInfo.Email != newEmail)
{
if (!Users.ValidateEmail(newEmail, uid))
{
ResponseText("{'text':'Email: \"" + newEmail + "\" 已经被其它用户注册使用','code':0}");
return;
}
userInfo.Email = newEmail;
Users.UpdateUserProfile(userInfo);
}
Emails.DiscuzSmtpMail(userInfo.Username, newEmail, string.Empty, userInfo.Authstr);
ResponseText("{'text':'验证邮件已经重新发送到您指定的E-mail地址当中','code':1}");
}




#region Helper
/// <summary>
/// 向页面输出xml内容
/// </summary>
/// <param name="xmlnode">xml内容</param>
private void ResponseXML(System.Text.StringBuilder xmlnode)
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "Text/XML";
System.Web.HttpContext.Current.Response.Expires = 0;
System.Web.HttpContext.Current.Response.Cache.SetNoStore();
System.Web.HttpContext.Current.Response.Write(xmlnode.ToString());
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
//System.Web.HttpContext.Current.Response.End();
}


/// <summary>
/// 输出json内容
/// </summary>
/// <param name="json"></param>
private void ResponseJSON(string json)
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "application/json";
System.Web.HttpContext.Current.Response.Expires = 0;
System.Web.HttpContext.Current.Response.Cache.SetNoStore();
System.Web.HttpContext.Current.Response.Write(json);
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
//System.Web.HttpContext.Current.Response.End();
}


private void ResponseJSON<T>(T jsonobj)
{
ResponseJSON(JavaScriptConvert.SerializeObject(jsonobj));
}
#endregion


} //class
//namespace

这样就完成了图片上传的功能。如果遇到什么问题的话。qq:312931671联系我

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值