JAVA工具
JAVA使用软件 开发工具
posts - 87,  comments - 9,  trackbacks - 0

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Common;
using Common.Assignment;
using Common.Attachment;
using Common.Log;
using Common.TBL;
using websiteCore.LINQ.ULT;
using websiteCore.LINQ.ATC;
using websiteCore.Common;

namespace WebPartLib._layouts.website_Resources.ExtPages
{
    public partial class UploadService : System.Web.UI.Page
    {
        protected string strJson = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Request["Id"];
            string action = Request["action"];
            string knowledge_id = Request["lid"];

            if (action != null)
            {
                if ("upload".Equals(action))
                {
                    UploadAttachment(HttpContext.Current, knowledge_id);
                    //UoloadAttachment2(HttpContext.Current, knowledge_id);
                }
                else if ("DownLoad".Equals(action))
                {
                    DownLoadAttachment(HttpContext.Current, id);
                }
            }
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="knowledge_id"></param>
        private void DownLoadAttachment(HttpContext context, string attachmentId)
        {
            try
            {
                if (!string.IsNullOrEmpty(attachmentId))
                {
                    using (var atcContext = ATCDBHelper.DataContext)
                    {
                        //CommonUtil.AddAppErrorLog("CHG000001136", "BPS", "BEGIN_DOWNLOAD" + attachmentId, null);
                        var obj = atcContext.Usp_ATC_DownLoadAttachmentContent(attachmentId).FirstOrDefault();
                        //CommonUtil.AddAppErrorLog("CHG000001136", "BPS", "END_DOWNLOAD", null);
                        string attachmentName = obj.AttachmentName;
                        byte[] data = obj.AttachmentContent.ToArray();
                       
                        //获得文件后缀
                        int index = attachmentName.LastIndexOf(".");
                        string suffixal = attachmentName.Substring((index + 1), attachmentName.Length - (index + 1));

                        string contextType = "";
                        switch (suffixal)
                        {
                            case "xls":
                            case "xlsx":
                                contextType = "application/vnd.ms-excel";
                                break;
                            case "jpeg":
                            case "jpg":
                            case "jpe":
                            case "png":
                            case "tif":
                            case "tiff":
                            case "gif":
                                contextType = "image/jpeg";
                                break;
                            case "docx":
                            case "doc":
                                contextType = "application/msword";
                                break;
                            case "pdf":
                                contextType = "application/pdf";
                                break;
                            case "ppt":
                                contextType = "application/vnd.ms-powerpoint";
                                break;
                            case "js":
                                contextType = "application/x-javascript";
                                break;
                            case "zip":
                                contextType = "application/zip";
                                break;
                            default:
                                contextType = "application/octet-stream";
                                break;
                        }
                        context.Response.ContentType = contextType;

                        context.Response.Charset = "GB2312";
                        context.Response.ContentEncoding = System.Text.Encoding.UTF8;

                        //string srcName = System.Web.HttpUtility.UrlEncode(attachmentName);
                        //string tagName = System.Web.HttpUtility.UrlDecode(srcName, System.Text.Encoding.UTF8);

                        //System.Text.Encoding uft8 = System.Text.Encoding.UTF8;// GetEncoding(65001);
                        ////System.Text.Encoding gb2312 = System.Text.Encoding.GetEncoding("GB2312");
                        //byte[] strTemp1 = System.Text.Encoding.Default.GetBytes(attachmentName); ;
                        //byte[] strTemp2 = System.Text.Encoding.Convert(System.Text.Encoding.Default, System.Text.Encoding.UTF8, strTemp1);
                        //string FileName = uft8.GetString(strTemp2);


                        //if (strTemp.Length > 150)
                        //{
                        //}
                        //System.Text.Encoding iso8859, gb2312;
                        //iso8859 = System.Text.Encoding.GetEncoding("ISO8859-1");
                        //gb2312 = System.Text.Encoding.UTF8;
                        //byte[] gb2;
                        //gb2 = gb2312.GetBytes(attachmentName);
                        //string iso = iso8859.GetString(gb2);

                        Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(attachmentName));
                        //Response.AddHeader("Content-Disposition", "attachment;filename=" + tagName);
                        Response.AddHeader("Content-Length", data.Length.ToString());
                        if (data.Length > 0)
                        {
                            Response.BinaryWrite(data);
                        }
                        context.ApplicationInstance.CompleteRequest();
                    }
                }
            }
            catch(Exception err)
            {
                CommonUtil.AddAppErrorLog("CHG000001136", "BPS", "DOWNLOAD_ERROR" + err.Message, null);
                Response.StatusCode = 500;
            }
        }

        //上传附件控件2
        private void UoloadAttachment2(HttpContext context, string knowledge_id)
        {
           JSONHelper jsonHelper = new JSONHelper();

            string account = CommonMethods.IdentityName();
            string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
            string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
            string strFileNameNoExt = Path.GetFileNameWithoutExtension(context.Request.Files[0].FileName);

            Stream stream = context.Request.Files[0].InputStream;
            var fileLength = Math.Round((double)stream.Length / 1024, 2);
            //文件过大禁止上传
            if (fileLength > 10240)
            {
                jsonHelper.AddItem("status_error", "上传文件不能超过10M.");
                jsonHelper.ItemOk();
            }
            else
            {
                //保存
               string dirPath = Server.MapPath("~/website_Upload");
               string tmp=DateTime.Now.ToString("yyyyMMdd");
               string filetype=knowledge_id.Substring(0, 3);

               dirPath += "\\" + filetype + "\\" + tmp.Substring(0, 4) + "\\" + tmp.Substring(4, 2);

               string filePath = "website_Upload/" + filetype + "/" + tmp.Substring(0, 4) + "/" + tmp.Substring(4, 2);

               if (!Directory.Exists(dirPath))
               {
                   Directory.CreateDirectory(dirPath);
               }

               dirPath += "\\" + strFileName;
               filePath += "/" + strFileName;

               context.Request.Files[0].SaveAs(dirPath);
                jsonHelper.AddItem("status_error", "OK");
                jsonHelper.AddItem("url", filePath);
                jsonHelper.AddItem("name", strFileName);
                jsonHelper.AddItem("ext", strExtension);
                jsonHelper.AddItem("filesize", fileLength.ToString());
                jsonHelper.AddItem("uploader", CommonMethods.GetUserName(account));
                jsonHelper.ItemOk();
            }
            strJson = jsonHelper.ToString();
        }
       
        /// <summary>
        /// 上传附件控制
        /// </summary>
        /// <param name="context"></param>
        /// <param name="knowledge_id"></param>
        private void UploadAttachment(HttpContext context, string knowledge_id)
        {
            JSONHelper jsonHelper = new JSONHelper();

            int attachmentType = 0;
            int.TryParse(context.Request["attachmentType"], out attachmentType);
            string account = CommonMethods.IdentityName();
            string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
            string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
            string strFileNameNoExt = Path.GetFileNameWithoutExtension(context.Request.Files[0].FileName);

            Stream stream = context.Request.Files[0].InputStream;
            var fileLength = Math.Round((double)stream.Length / 1024, 2);
            //文件过大禁止上传
            if (fileLength > 10240)
            {
                jsonHelper.AddItem("status_error", "上传文件不能超过10M.");
                jsonHelper.ItemOk();
            }
            else
            {
                //int currentVer = 0;
                ////检查文件名是否已经存在,如果存在需要在后面加(1),(2)...
                //using (var dataContext = ULTDBHelper.DataContext)
                //{
                //    var obj = (from r in dataContext.Tbl_UltAttachment
                //               where r.AttachmentName.Trim().Equals(strFileName.Trim())
                //               orderby r.FileLastV descending
                //               select r.FileLastV).FirstOrDefault();

                //    //已经存在相同的文件名
                //    if (obj != null)
                //    {
                //        currentVer = obj.Value;
                //        //增加文件后缀数
                //        currentVer = currentVer + 1;
                //        strFileName = strFileNameNoExt + "(" + currentVer.ToString() + ")" + strExtension;
                //    }
                //}

                //存入MOSS数据库
                //WssField[] fields = new WssField[] {
                //    new WssField { fieldName = AttachmentService.FORMID, fieldValue = knowledge_id},
                //    new WssField { fieldName = AttachmentService.NAME, fieldValue = strFileNameNoExt},//shortName},                   
                //    new WssField { fieldName = AttachmentService.SIZE, fieldValue = fileLength},
                //    new WssField { fieldName = AttachmentService.LABELID, fieldValue = "5"},
                //    new WssField { fieldName = AttachmentService.CREATOR, fieldValue = account},
                //    new WssField { fieldName = AttachmentService.CREATETIME, fieldValue = DateTime.Now},
                //    new WssField { fieldName = AttachmentService.FLAG, fieldValue = " "}
                //};
                /******************* modify by xml *********************
                 * 从2011.11.15号起附件存入SQLServer 2005,不存入MOSS中
                 */
                using (var ultContext = ULTDBHelper.DataContext)
                {
                    try
                    {
                        byte[] data = new byte[stream.Length];
                        int length = data.Length;
                        stream.Read(data, 0, length);
                        stream.Close();

                        //存入website_database下的tbl_UltAttachment,获得附件编号attachmentId
                        string attachmentId = string.Empty;
                        ultContext.Usp_ULT_SaveAttachment(
                                    knowledge_id,
                                    attachmentType,
                                    strFileName,
                                    "SQLServer2005",
                                    account,
                                    (decimal)fileLength,
                                    0,
                                    0,
                                    ref attachmentId);
                        //将内容存入website_attachment_database
                        using(var atcContext = ATCDBHelper.DataContext)
                        {
                            atcContext.Usp_ATC_UpdateAttachmentContent(attachmentId, data);
                        }
                        //Response.Write("{success: true}");
                        jsonHelper.AddItem("status_error", "OK");
                        jsonHelper.AddItem("Id", attachmentId);
                        jsonHelper.AddItem("fileId", "KBA" + attachmentId);
                        jsonHelper.AddItem("url", "_layouts/website_Resources/ExtPages/UploadService.aspx?action=DownLoad&id=");
                        jsonHelper.AddItem("name", strFileName);
                        jsonHelper.AddItem("uploader", CommonMethods.GetUserName(account));
                        jsonHelper.AddItem("filesize", fileLength.ToString());
                        jsonHelper.ItemOk();

                    }
                    catch
                    {

                        jsonHelper.AddItem("status_error", "OK");
                        jsonHelper.ItemOk();
                    }
                }

                //string linkName = string.Empty;
                //string value = AttachmentService.Instance.UploadAttachment(stream, knowledge_id, strFileName, out linkName, fields);
                ////防止页面出现id冲突
                //jsonHelper.AddItem("status_error", "OK");
                //jsonHelper.AddItem("Id", value);
                //jsonHelper.AddItem("fileId", "KBA" + value);
                //jsonHelper.AddItem("url", linkName);
                //jsonHelper.AddItem("name", strFileNameNoExt + strExtension);
                //jsonHelper.AddItem("ext", strExtension);
                //jsonHelper.AddItem("filesize", fileLength.ToString());
                //jsonHelper.AddItem("uploader", CommonMethods.GetUserName(account));
                //jsonHelper.AddItem("fileLastV", currentVer.ToString());

                //jsonHelper.ItemOk();
            }

            strJson = jsonHelper.ToString();
        }
    }
}

posted on 2011-09-16 16:48 王豪 阅读(446) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 

常用链接

留言簿

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜