关于Dynamic附件上传的那些事儿!

来源:互联网 发布:c语言的主函数类型 编辑:程序博客网 时间:2024/05/18 13:09

       每次做以Dynamic为后台(portal,app)时,最头痛的是附件上传功能,由于一直以来是将附件上传到服务器的某个目录的然后将文件挂载在IIS上,如果有负载均衡的话,还得把文件上传到一个共享目录,这样做起来会非常麻烦;然而每个项目的服务器配置又不一样这样附件上传功能就更不好通用,就算能通用配置起来也比较麻烦。俗话说只有想不到的没有办不到的。换个思路,如果将附件保存在数据库中这样不同的项目只需要更改数据库连接这样不就更省事儿了么?恰巧的是Dynamic CRM是有附件实体直接用的。这里奉上代码:

    附件上传

   
            HttpFileCollection files = Request.Files;
            BaseModel model = new BaseModel();
            JSONHelper jsdb = new JSONHelper();
            try
            {
                int entitycode = 0;
                CRMService service = new CRMService();
                DBHelper db = new DBHelper();
                string entityid = Request.Form["entityid"];
                string entityname = Request.Form["entityname"];
                if (!string.IsNullOrEmpty(entityid) && !string.IsNullOrEmpty(entityname) && files.Count > 0)
                {
                    string sql = "select ObjectTypeCode from Entity where name='" + entityname + "'";
                    SqlDataReader dr = db.ExecuteReader(sql);
                    if (dr.Read())
                    {
                        entitycode = int.Parse(dr["ObjectTypeCode"].ToString());
                    }
                    string returnValue = string.Empty;
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile postedFile = files[i];
                        if (postedFile.ContentLength != 0)
                        {
                            string filename = Path.GetFileName(postedFile.FileName);
                            string filetype = postedFile.ContentType;
                            byte[] FileByte = StreamToBytes(postedFile.InputStream);
                            Entity ent = new Entity("annotation");
                            ent["objecttypecode"] = entitycode;
                            ent["objectid"] = new EntityReference(entityname, new Guid(entityid));
                            ent["isdocument"] = false;
                            ent["mimetype"] = filetype;
                            ent["documentbody"] = Convert.ToBase64String(FileByte); ;
                            ent["filesize"] = postedFile.ContentLength;
                            ent["filename"] = filename;
                            service.Service.Create(ent);
                        }
                        else
                        {
                            model.input(10, "文件不能为空!");
                        }
                    }
                }
                else
                {
                    //上传失败
                    model.input(10, "文件和实体名称和实体id不能为空!");
                }

            }
            catch (Exception ex)
            {
                if (ex.Message == "Creating Entity with an invalid parent. Entity: Annotation, ReferencingAttribute:objectid")
                    model.input(10, "该实体不允许上传附件,请联系系统管理员,设置实体注释和活动可添加!");
                else
                    model.input(10, ex.Message);
            }
            Response.Write(jsdb.ObjectToJSON(model));

附件下载:

       //string id = Request.QueryString["id"].ToString();//附件id即Annotationid
            string id = "25D5C550-BF9D-E711-80E2-00155D862B00";
            BaseModel model = new BaseModel();
            CRMService service = new CRMService();
            DBHelper db = new DBHelper();
            try
            {
                if (!string.IsNullOrEmpty(id))
                {
                    string sql = @"select Annotationid, ObjectTypeCode,ObjectId,Subject,isdocument,NoteText,MimeType,langid,DocumentBody
                                    ,filesize,filename from Annotation
                                    where Annotationid='"+id+@"' ";

                    SqlDataReader dr = db.ExecuteReader(sql);
                    if (dr.Read())
                    {
                        string FileContent = dr["DocumentBody"].ToString();
                        if (!string.IsNullOrEmpty(FileContent))
                        {
                            byte[] byteArray = Convert.FromBase64String(FileContent);
                           
                            //先将二进制字符写入临时文件
                            string temppath = HttpContext.Current.Server.MapPath("/Temp/" + dr["filename"].ToString());
                            if (System.IO.File.Exists(temppath))
                            {
                                System.IO.File.Delete(temppath);
                            }

                            FileStream fstemp = new FileStream(temppath, FileMode.CreateNew);
                            BinaryWriter bw = new BinaryWriter(fstemp);
                            bw.Write(byteArray, 0, byteArray.Length);
                            bw.Close();
                            fstemp.Close();

                            //以字符流的形式下载文件
                            FileStream fs = new FileStream(temppath, FileMode.Open);                          
                            fs.Read(byteArray, 0, byteArray.Length);
                            fs.Close();
                            Response.ContentType = "application/octet-stream";
                            //通知浏览器下载文件而不是打开
                            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dr["filename"].ToString(), System.Text.Encoding.UTF8));
                            Response.BinaryWrite(byteArray);
                            Response.Flush();
                            //删除临时文件
                            if (System.IO.File.Exists(temppath))
                            {
                                System.IO.File.Delete(temppath);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                model.input(10, ex.Message);
            }



原创粉丝点击