Example #1
0
        /// <summary>
        /// 检查上传的图片是否合法
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="errors"></param>
        public static void checkUploadPic( HttpFile postedFile, Result errors )
        {
            if (postedFile == null) {
                errors.Add( lang.get( "exPlsUpload" ) );
                return;
            }

            // 检查文件大小
            if (postedFile.ContentLength <= 1) {
                errors.Add( lang.get( "exPlsUpload" ) );
                return;
            }

            int uploadMax = 1024 * 1024 * config.Instance.Site.UploadPicMaxMB;
            if (postedFile.ContentLength > uploadMax) {
                errors.Add( lang.get( "exUploadMax" ) + " " + config.Instance.Site.UploadPicMaxMB + " MB" );
                return;
            }

            // TODO: (flash upload) application/octet-stream
            //if (postedFile.ContentType.ToLower().IndexOf( "image" ) < 0) {
            //    errors.Add( lang.get( "exPhotoFormatTip" ) );
            //    return;
            //}

            // 检查文件格式
            if (Uploader.isAllowedPic( postedFile ) == false) {
                errors.Add( lang.get( "exUploadType" ) + ":" + postedFile.FileName + "(" + postedFile.ContentType + ")" );
            }
        }
Example #2
0
 static void CometWorker_FileUploadRequested(ref HttpFile file)
 {
     string fileName = file.ServerMapPath + "\\Upload\\" + file.FileName;
     file.SaveAs(fileName);
     string resourceName = file.FileName.Replace("&", "_");
     ResourceManager.AddReplaceResource(fileName, resourceName, ResourceType.Image, file.ClientId);
     CometWorker.SendToClient(file.ClientId, JSON.Method("ShowImage", resourceName));
 }
Example #3
0
		public void TestDisposedFilename()
		{
			HttpFile file = new HttpFile("object", "object", "object");
			file.Dispose();

			#pragma warning disable 168
		    Assert.Throws(typeof (ObjectDisposedException), delegate { string tmp = file.Filename; });
			#pragma warning restore 168
		}
Example #4
0
		/// <summary> Test to make sure files gets deleted upon disposing </summary>
		public void TestFileDeletion()
		{
			string path = Environment.CurrentDirectory + "\\tmptest";
			HttpFile file = new HttpFile("testFile", path, "nun");

			File.WriteAllText(path, "test");
			file.Dispose();

			Assert.Equal(File.Exists(path), false);
		}
Example #5
0
		public void TestModifications()
		{
			HttpFile file = new HttpFile("testFile", "nun", "nun");
			_form.AddFile(file);
			Assert.Equal(file, _form.GetFile("testFile"));

			_form.Add("valueName", "value");
			Assert.Equal("value", _form["valueName"].Value);

			_form.Clear();
			Assert.Null(_form.GetFile("testFile"));
			Assert.Null(_form["valueName"].Value);
		}
        private AttachmentTemp savePostData( HttpFile postedFile, Result result ) {
            // 将附件存入数据库
            AttachmentTemp uploadFile = new AttachmentTemp();
            uploadFile.FileSize = postedFile.ContentLength;
            uploadFile.Type = postedFile.ContentType;
            uploadFile.Name = result.Info.ToString();
            uploadFile.Description = ctx.Post( "FileDescription" );
            uploadFile.ReadPermission = ctx.PostInt( "FileReadPermission" );
            uploadFile.Price = ctx.PostInt( "FilePrice" );
            uploadFile.AppId = ctx.app.Id;

            attachService.CreateTemp( uploadFile, (User)ctx.viewer.obj, ctx.owner.obj );
            return uploadFile;
        }
Example #7
0
        /// <summary>
        /// 是否允许的格式
        /// </summary>
        /// <param name="pfile"></param>
        /// <returns></returns>
        public static Boolean IsAllowedPic( HttpFile pfile )
        {
            String[] types = { "jpg", "gif", "bmp", "png", "jpeg" };
            String[] cfgTypes = config.Instance.Site.UploadPicTypes;
            if (cfgTypes != null && cfgTypes.Length > 0) types = cfgTypes;

            if (containsChar( cfgTypes, "*" )) return true;

            foreach (String ext in types) {
                if (strUtil.IsNullOrEmpty( ext )) continue;
                String extWithDot = ext.StartsWith( "." ) ? ext : "." + ext;
                if (strUtil.EqualsIgnoreCase( Path.GetExtension( pfile.FileName ), extWithDot )) return true;
            }

            return false;
        }
Example #8
0
        /// <summary>
        /// 检查上传的图片是否合法
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="errors"></param>
        public static void CheckUploadPic( HttpFile postedFile, Result errors )
        {
            if (postedFile == null) {
                errors.Add( lang.get( "exPlsUpload" ) );
                return;
            }

            // 检查文件大小
            if (postedFile.ContentLength <= 1) {
                errors.Add( lang.get( "exPlsUpload" ) );
                return;
            }

            int uploadMax = 1024 * 1024 * config.Instance.Site.UploadPicMaxMB;
            if (postedFile.ContentLength > uploadMax) {
                errors.Add( lang.get( "exUploadMax" ) + " " + config.Instance.Site.UploadPicMaxMB + " MB" );
                return;
            }

            // 检查文件格式
            if (Uploader.IsAllowedPic( postedFile ) == false) {
                errors.Add( lang.get( "exUploadType" ) + ":" + postedFile.FileName + "(" + postedFile.ContentType + ")" );
            }
        }
Example #9
0
        /// <summary>
        /// 保存上传的图片
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="arrThumbType"></param>
        /// <returns></returns>
        public static Result SaveImg( HttpFile postedFile, Dictionary<String, ThumbInfo> arrThumbType )
        {
            Result result = new Result();

            CheckUploadPic( postedFile, result );
            if (result.HasErrors) {
                logger.Info( result.ErrorsText );
                return result;
            }

            String pathName = PathHelper.Map( sys.Path.DiskPhoto );
            String photoName = Img.GetPhotoName( pathName, postedFile.ContentType );
            String filename = Path.Combine( pathName, photoName );

            try {
                postedFile.SaveAs( filename );

                foreach (KeyValuePair<String, ThumbInfo> kv in arrThumbType) {
                    Boolean isValid = SaveThumbSingle( filename, kv.Key, kv.Value );
                    if (!isValid) {
                        file.Delete( filename );
                        result.Add( "format error: " + postedFile.FileName );
                        return result;
                    }
                }

            }
            catch (Exception exception) {
                logger.Error( lang.get( "exPhotoUploadError" ) + ":" + exception.Message );
                result.Add( lang.get( "exPhotoUploadErrorTip" ) );
                return result;
            }
            result.Info = photoName.Replace( @"\", "/" );
            return result;
        }
        private PhotoPost savePicPrivate( HttpFile postedFile, Result result )
        {
            PhotoPost post = new PhotoPost();
            post.OwnerId = ctx.owner.Id;
            post.OwnerType = ctx.owner.obj.GetType().FullName;
            post.OwnerUrl = ctx.owner.obj.Url;

            post.Creator = (User)ctx.viewer.obj;
            post.CreatorUrl = ctx.viewer.obj.Url;
            post.DataUrl = result.Info.ToString();
            post.Title = strUtil.CutString( Path.GetFileNameWithoutExtension( postedFile.FileName ), 20 );
            post.Ip = ctx.Ip;
            post.PhotoAlbum = new PhotoAlbum();

            postService.CreatePostTemp( post );
            return post;
        }
Example #11
0
 /// <summary>
 /// 保存上传的图片
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Result SaveImg( HttpFile postedFile )
 {
     return SaveImg( postedFile, ThumbConfig.GetPhotoConfig() );
 }
Example #12
0
        private static Boolean isAllowedFile( HttpFile pfile )
        {
            String[] types = { "zip", "7z", "rar" };
            String[] cfgTypes = config.Instance.Site.UploadFileTypes;
            if (cfgTypes != null && cfgTypes.Length > 0) types = cfgTypes;

            foreach (String ext in types) {
                if (strUtil.IsNullOrEmpty( ext )) continue;
                String extWithDot = ext.StartsWith( "." ) ? ext : "." + ext;
                if (strUtil.EqualsIgnoreCase( Path.GetExtension( pfile.FileName ), extWithDot )) return true;
            }

            return false;
        }
Example #13
0
 /// <summary>
 /// 保存上传的图片
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Result SaveImg(HttpFile postedFile)
 {
     return(SaveImg(postedFile, ThumbTypes));
 }
Example #14
0
        public HubModule(IDbConnection db, ILog log, IRootPathProvider pathProvider)
            : base("/hub")
        {
            this.RequiresAuthentication();

            Get["/"] = parameters => {
                Page.Title = "HUB首页";
                return(Response.AsRedirect("/hub/printer"));
                //return View["Index", Model];
            };

            Get["/add"] = parameters => {
                Page.Title = "成为HUB";
                var supplierId = db.Single <string>("select SupplierId from t_user where id=@id limit 1",
                                                    new { id = Page.UserId });
                //已经是hub了
                if (!string.IsNullOrEmpty(supplierId))
                {
                    return(Response.AsRedirect("/hub"));
                }

                var expresses = db.Select <ExpressModel>("select ExpressId,Fname from t_express");

                var supplierModel = new SupplierModel();
                supplierModel.Ftype = "0";
                Model.SupplierModel = supplierModel;
                Model.Expresses     = expresses;
                Model.countNoAudit  = CountNoAudit(db);
                return(View["Add", Model]);
            };

            Post["/add"] = parameters => {
                var supplierId = db.Single <string>("select SupplierId from t_user where id=@id limit 1",
                                                    new { id = Page.UserId });
                //已经是hub了
                if (!string.IsNullOrEmpty(supplierId))
                {
                    throw new Exception("已经是hub(供应商)了");
                }

                var model = this.Bind <SupplierModel>();
                model.SupplierId = Guid.NewGuid().ToString("N");
                var result = this.Validate(model);
                if (!result.IsValid)
                {
                    foreach (var item in result.Errors)
                    {
                        foreach (var member in item.Value)
                        {
                            base.Page.Errors.Add(new ErrorModel()
                            {
                                Name = item.Key, ErrorMessage = member.ErrorMessage
                            });
                        }
                    }
                }

                var      files = Request.Files;
                HttpFile file_Logo = null, file_IdCarPic1 = null, file_IdCarPic2 = null, file_BlicensePic = null;
                foreach (var file in files)
                {
                    if (file.Key == "Logo")
                    {
                        file_Logo = file;
                    }
                    if (file.Key == "IdCarPic1")
                    {
                        file_IdCarPic1 = file;
                    }
                    if (file.Key == "IdCarPic2")
                    {
                        file_IdCarPic2 = file;
                    }
                    if (file.Key == "BlicensePic")
                    {
                        file_BlicensePic = file;
                    }
                }

                string uploadDirectory;

                if (file_Logo == null)
                {
                    Page.Errors.Add(new ErrorModel()
                    {
                        Name = "", ErrorMessage = "Logo不能为空"
                    });
                }
                else
                {
                    uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "supplier", "logo");
                    if (!Directory.Exists(uploadDirectory))
                    {
                        Directory.CreateDirectory(uploadDirectory);
                    }
                    string   _filename = "", filename = "";
                    string[] imgs = new string[] { ".jpg", ".png", ".gif", ".bmp", ".jpeg" };
                    if (!imgs.Contains(System.IO.Path.GetExtension(file_Logo.Name).ToLower()))
                    {
                        Page.Errors.Add(new ErrorModel()
                        {
                            Name = "", ErrorMessage = "Logo文件格式不正确"
                        });
                    }
                    _filename = model.SupplierId + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file_Logo.Name;
                    filename  = Path.Combine(uploadDirectory, _filename);
                    using (FileStream fileStream = new FileStream(filename, FileMode.Create)) {
                        file_Logo.Value.CopyTo(fileStream);
                    }

                    model.Logo = _filename;
                }

                //个人
                if (model.Ftype == "0")
                {
                    Regex reg = new Regex(@"(^\d{18}$)|(^\d{15}$)");
                    if (model.IdCard == null || !reg.IsMatch(model.IdCard))
                    {
                        Page.Errors.Add(new ErrorModel()
                        {
                            Name = "", ErrorMessage = "身份证号码格式不正确"
                        });
                    }

                    if (file_IdCarPic1 == null || file_IdCarPic2 == null)
                    {
                        Page.Errors.Add(new ErrorModel()
                        {
                            Name = "", ErrorMessage = "身份证扫描不能为空"
                        });
                    }
                    else
                    {
                        uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "supplier", "idpic");
                        if (!Directory.Exists(uploadDirectory))
                        {
                            Directory.CreateDirectory(uploadDirectory);
                        }
                        string   _filename = "", filename = "";
                        string[] imgs = new string[] { ".jpg", ".png", ".gif", ".bmp", ".jpeg" };
                        if (!imgs.Contains(System.IO.Path.GetExtension(file_IdCarPic1.Name).ToLower()) ||
                            !imgs.Contains(System.IO.Path.GetExtension(file_IdCarPic2.Name).ToLower())
                            )
                        {
                            Page.Errors.Add(new ErrorModel()
                            {
                                Name = "", ErrorMessage = "身份证扫描文件格式不正确"
                            });
                        }
                        _filename = model.SupplierId + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file_IdCarPic1.Name;
                        filename  = Path.Combine(uploadDirectory, _filename);
                        using (FileStream fileStream = new FileStream(filename, FileMode.Create)) {
                            file_IdCarPic1.Value.CopyTo(fileStream);
                        }

                        model.IdCardPic1 = _filename;

                        _filename = model.SupplierId + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file_IdCarPic2.Name;
                        filename  = Path.Combine(uploadDirectory, _filename);
                        using (FileStream fileStream = new FileStream(filename, FileMode.Create)) {
                            file_IdCarPic2.Value.CopyTo(fileStream);
                        }

                        model.IdCardPic2 = _filename;
                    }
                }

                //企业
                if (model.Ftype == "1")
                {
                    if (model.CompanyName == null || model.CompanyName.Trim().Length < 2)
                    {
                        Page.Errors.Add(new ErrorModel()
                        {
                            Name = "", ErrorMessage = "请正确填写企业名称"
                        });
                    }
                    if (model.Capital == null || model.Capital.Trim() == "")
                    {
                        Page.Errors.Add(new ErrorModel()
                        {
                            Name = "", ErrorMessage = "注册资本不能为空"
                        });
                    }
                    if (model.Fcode == null || model.Fcode.Trim() == "")
                    {
                        Page.Errors.Add(new ErrorModel()
                        {
                            Name = "", ErrorMessage = "统一代码不能为空"
                        });
                    }

                    if (file_BlicensePic == null)
                    {
                        Page.Errors.Add(new ErrorModel()
                        {
                            Name = "", ErrorMessage = "营业执照扫描件不能为空"
                        });
                    }
                    else
                    {
                        uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "supplier",
                                                       "idpic");
                        if (!Directory.Exists(uploadDirectory))
                        {
                            Directory.CreateDirectory(uploadDirectory);
                        }
                        string   _filename = "", filename = "";
                        string[] imgs = new string[] { ".jpg", ".png", ".gif", ".bmp", ".jpeg" };
                        if (!imgs.Contains(System.IO.Path.GetExtension(file_BlicensePic.Name).ToLower()))
                        {
                            Page.Errors.Add(new ErrorModel()
                            {
                                Name = "", ErrorMessage = "身份证扫描文件格式不正确"
                            });
                        }
                        _filename = model.SupplierId + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" +
                                    file_BlicensePic.Name;
                        filename = Path.Combine(uploadDirectory, _filename);
                        using (FileStream fileStream = new FileStream(filename, FileMode.Create)) {
                            file_BlicensePic.Value.CopyTo(fileStream);
                        }

                        model.BlicensePic = _filename;
                    }
                }

                if (Page.Errors.Count > 0)
                {
                    //验证不通过时,删除本次上传的文件以防止冗余
                    if (model.Logo != null)
                    {
                        System.IO.File.Delete(Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "supplier",
                                                           "logo",
                                                           model.Logo));
                    }
                    if (model.IdCardPic1 != null)
                    {
                        System.IO.File.Delete(Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "supplier",
                                                           "idpic",
                                                           model.IdCardPic1));
                    }
                    if (model.IdCardPic2 != null)
                    {
                        System.IO.File.Delete(Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "supplier",
                                                           "idpic",
                                                           model.IdCardPic2));
                    }
                    if (model.BlicensePic != null)
                    {
                        System.IO.File.Delete(Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "supplier",
                                                           "idpic",
                                                           model.BlicensePic));
                    }

                    Model.SupplierModel = model;
                    return(View["Add", Model]);
                    //return Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest);
                }

                //通过地址,从百度返回经纬度坐标
                string    url = $"http://api.map.baidu.com/geocoder/v2/?address={model.Address}&output=json&ak=26904d2efeb684d7d59d493098e7295d";
                WebClient wc  = new WebClient();
                wc.Encoding = Encoding.UTF8;
                string  json = wc.DownloadString(url);
                JObject m    = JObject.Parse(json);
                if (m["status"].ToString() == "0")
                {
                    model.Lng = m["result"]["location"]["lng"].ToString(); //经度
                    model.Lat = m["result"]["location"]["lat"].ToString(); //纬度
                }


                string sql = $@"
                    INSERT INTO t_supplier (
                        SupplierId,
                        Tel,
                        QQ,
                        Address,
                        Logo,
                        IdCard,
                        Fname,
                        IdCardPic1,
                        IdCardPic2,
                        CompanyName,
                        Capital,
                        Fcode,
                        BlicensePic,
                        Ftype,
                        Lng,
                        Lat,
                        ExpressId
                    )VALUES(
                        '{model.SupplierId}',
                        '{model.Tel}',
                        '{model.QQ}',
                        '{model.Address}',
                        '{model.Logo}',
                        '{model.IdCard}',
                        '{model.Fname}',
                        '{model.IdCardPic1}',
                        '{model.IdCardPic2}',
                        '{model.CompanyName}',
                        '{model.Capital}',
                        '{model.Fcode}',
                        '{model.BlicensePic}',
                        '{model.Ftype}',
                        '{model.Lng}',
                        '{model.Lat}',
                        '{model.ExpressId}'
                        );
                    UPDATE t_user SET SupplierId='{model.SupplierId}' where id='{Page.UserId}';                       
                ";
                db.ExecuteNonQuery(sql);
                Model.Message = "添加Hub成功!";
                Model.Url     = "/hub";
                return(View["Success", Model]);
            };

            Get["/edit"] = parameters => {
                var supplier = db.Single <SupplierModel>($@"
                    select Tel,
                        QQ,
                        Address,
                        Logo,
                        IdCard,
                        Fname,
                        IdCardPic1,
                        IdCardPic2,
                        CompanyName,
                        Capital,
                        Fcode,
                        BlicensePic,
                        Ftype,
                        Lng,
                        Lat,
                        ExpressId 
                    from t_supplier where supplierId=(select SupplierId from t_user where id=@id limit 1)",
                                                         new { id = Page.UserId });
                var expresses = db.Select <ExpressModel>("select ExpressId,Fname from t_express");
                Model.Expresses     = expresses;
                Model.countNoAudit  = CountNoAudit(db);
                Model.SupplierModel = supplier;

                return(View["Edit", Model]);
            };

            Post["/edit"] = parameters => {
                return(null);
            };

            Get["/printer.js"] = parameters => {
                string str      = "var printers = [";
                var    printers = db.Select <PrinterModel>("SELECT PrinterId,Fname FROM t_printer WHERE State='0'");
                printers.ForEach(i => {
                    str = str + $@"{{value:'{i.PrinterId}',label:'{i.Fname}'}},";
                });
                str = str.TrimEnd(',') + "];";
                return(Response.AsText(str));
            };

            Get["/printer"] = parameters => {
                string sql = "select AccuracyId,Fname from t_printaccuracy;";
                var    printerAccuracys = db.Select <PrinterAccuracyModel>(sql);
                sql = "select CompleteId,Fname from t_printcomplete;";
                var printerCompletes = db.Select <PrinterCompleteModel>(sql);

                var accuracyOpt = "<select class='accuracyOpt'>";
                foreach (var item in printerAccuracys)
                {
                    accuracyOpt += "<option value='" + item.AccuracyId + "'>" + item.Fname + "</option>";
                }
                accuracyOpt += "</select>";

                var completeOpt = "<select class='completeOpt'>";
                foreach (var item in printerCompletes)
                {
                    completeOpt += "<option value='" + item.CompleteId + "'>" + item.Fname + "</option>";
                }
                completeOpt += "</select>";

                Model.accuracyOpt  = accuracyOpt;
                Model.completeOpt  = completeOpt;
                Model.countNoAudit = CountNoAudit(db);
                return(View["Print", Model]);
            };

            Get["/printer/material/list"] = parameters => {
                string sql = $@"
                    select t1.SupplierId ,t1.PrinterId, t2.fname as PrinterName, t1.State as PrinterState, t4.MaterialId,t4.Name as MaterialName
                    from t_supplier_printer t1
                    left join t_printer t2 on t2.printerid=t1.printerid
                    left join t_supplier_printer_material t3 on t3.SupplierId=t1.SupplierId  and t3.PrinterId=t2.PrinterId
                    left join t_material t4 on t4.MaterialId = t3.MaterialId
                    where                        
                        t2.state='0'
                        and t1.supplierid=(select SupplierId from t_user where id='{Page.UserId}')
                    order by t1.CreateTime desc;";
                var    supplierprintermaterials = db.Select <SupplierPrinterMaterialModel>(sql);
                return(Response.AsJson(
                           supplierprintermaterials
                           .GroupBy(i => new { i.SupplierId, i.PrinterId, i.PrinterName, i.PrinterState })
                           //.Select(x => new { printer = x.Key, result = x })
                           .Select(x => new {
                    printer = new {
                        SupplierId = x.Key.SupplierId,
                        PrinterId = x.Key.PrinterId,
                        PrinterName = x.Key.PrinterName,
                        PrinterState = x.Key.PrinterState == "0" ? "启用" : "禁用",
                    },
                    result = x
                })
                           , Nancy.HttpStatusCode.OK));
            };

            Post["/printer/material/{printerid}"] = parameters => {
                string printerid = parameters.printerid;
                string sql       = $@"
                    select t2.MaterialId,t2.Name
                    from t_supplier_printer_material t1
                    left join t_material t2 on t2.MaterialId = t1.MaterialId
                    where                        
                        t2.state='0'
                        and t1.supplierid=(select SupplierId from t_user where id='{Page.UserId}')
                        and t1.printerid='{printerid}'
                    order by t1.CreateTime desc;";
                var    materials = db.Select <Material>(sql);
                return(Response.AsJson(materials, Nancy.HttpStatusCode.OK));
            };

            Post["/printer/state"] = parameters => {
                string printerid = Request.Form.printerid;
                string stateid   = Request.Form.stateid;

                var message = "";
                if (stateid == "0")
                {
                    message = "启用成功";
                }
                if (stateid == "1")
                {
                    message = "禁用成功";
                }
                if (stateid == "2")
                {
                    message = "删除成功";
                }

                if (printerid == null || stateid == null)
                {
                    return(Response.AsJson(new { message = "状态值或打印机id为空!" }, Nancy.HttpStatusCode.BadRequest));
                }
                var stateids = new List <string> {
                    "0", "1", "2"
                };
                if (!stateids.Contains(printerid))
                {
                    return(Response.AsJson(new { message = "状态值不在范围内!" }, Nancy.HttpStatusCode.BadRequest));
                }

                string sql = $"update t_supplier_printer set state='{stateid}' where SupplierId=(select SupplierId from t_user where id='{Page.UserId}') and  PrinterId='{printerid}';";
                db.ExecuteNonQuery(sql);
                return(Response.AsJson(new { message = message }, Nancy.HttpStatusCode.OK));
            };

            Post["/printer/add"] = parameters => {
                string printerid = Request.Form.printerid;
                string sql       = $@"select count(1) 
                                from t_supplier_printer 
                                where SupplierId=(select SupplierId from t_user where id='{Page.UserId}') and  PrinterId='{printerid}' and State in ('0','1');";
                var    count     = db.Scalar <int>(sql);
                if (count > 0)
                {
                    return(Response.AsJson(new { message = "打印机已存在!" }, Nancy.HttpStatusCode.BadRequest));
                }

                sql   = $@"select count(1) 
                        from t_supplier_printer 
                        where SupplierId=(select SupplierId from t_user where id='{Page.UserId}') and  PrinterId='{printerid}' and State='2';";
                count = db.Scalar <int>(sql);
                if (count > 0)
                {
                    sql = $@"update t_supplier_printer set State='0' where SupplierId=(select SupplierId from t_user where id='{Page.UserId}') and  PrinterId='{printerid}';";
                    db.ExecuteNonQuery(sql);
                    return(null);
                }

                sql = $@"INSERT INTO t_supplier_printer (ID,SupplierId,PrinterId)
                                VALUES('{Guid.NewGuid().ToString("N")}',(select SupplierId from t_user where id='{Page.UserId}'),'{printerid}');";
                db.ExecuteNonQuery(sql);
                return(null);
            };

            Get["/material.js"] = parameters => {
                string str       = "var materials = [";
                var    materials = db.Select <Material>("SELECT * FROM t_material WHERE State='0'");
                materials.ForEach(i => {
                    str = str + $@"{{value:'{i.MaterialId}',label:'{i.Name}'}},";
                });
                str = str.TrimEnd(',') + "];";
                return(Response.AsText(str));
            };

            Get["/material/{id}"] = parameters => {
                var materialId = parameters.id;
                var material   = db.Single <Material>("select * from t_material where MaterialId=@MaterialId", new { MaterialId = materialId });
                return(Response.AsJson(material));
            };

            Post["/printer/material/add"] = parameters => {
                string printerid  = Request.Form.printerid;
                string materialid = Request.Form.materialid;
                string completeid = Request.Form.completeid;
                string accuracyid = Request.Form.accuracyid;
                string price      = Request.Form.price;
                string sql        = $@"select count(1) 
                    from t_supplier_printer_material
                    where SupplierId=(select SupplierId from t_user where id='{Page.UserId}') 
                        and  PrinterId='{printerid}'
                        and  MaterialId='{materialid}';";
                var    count      = db.Scalar <int>(sql);
                if (count > 0)
                {
                    return(Response.AsJson(new { message = "材料已存在!" }, Nancy.HttpStatusCode.BadRequest));
                }

                sql = $@"
                        INSERT INTO t_supplier_printer_material (
                            ID,
                            SupplierId,
                            PrinterId,
                            MaterialId,
                            CompleteId,
                            AccuracyId,
                            Price)
                        VALUES(
                            '{Guid.NewGuid().ToString("N")}',
                            (select SupplierId from t_user where id='{Page.UserId}'),
                            '{printerid}',
                            '{materialid}',
                            '{completeid}',
                            '{accuracyid}',
                            '{price}'
                        );";
                db.ExecuteNonQuery(sql);
                return(null);
            };

            Post["/printer/material/delete"] = parameters => {
                string printerid  = Request.Form.printerid;
                string materialid = Request.Form.materialid;
                string sql        = $@"
                    delete from t_supplier_printer_material 
                    where SupplierId=(select SupplierId from t_user where id='{Page.UserId}')
                        and PrinterId='{printerid}' and MaterialId='{materialid}';";
                db.ExecuteNonQuery(sql);
                return(null);
            };

            Get["/blance"] = parameters => {
                return(Response.AsText("账户余额", "text/html; charset=utf-8"));
            };

            Get["/order"] = parameters => {
                var orders = db.Select <OrderModel>($@"
                    select t1.OrderId,
                        t1.CreateTime,
                        t2.Amount,
                        t2.id as OrderDetailId,
                        t2.Area,
                        t2.Size,
                        t2.Volume,
                        t2.Weight,
                        t2.FileName,
                        t2.Num,
                        t2.Express,
                        t5.name as MatName,
                        t3.StateName,
                        t3.Id as StateId,
                        t4.Consignee,
                        t4.Address
                    from t_order t1
                    left join t_orderdetail  t2 on t2.OrderId=t1.OrderId
                    left join t_orderstate   t3 on t3.Id=t1.StateId
                    left join t_address  t4 on t4.Id=t1.AddressId
                    left join t_material  t5 on t5.MaterialId=t2.MaterialId
                    left join t_user t6 on t6.SupplierId=t2.SupplierId
                    where t6.Id='{Page.UserId}'
                    order by t1.EditTime desc")
                             //.GroupBy(i => new { i.OrderId, i.CreateTime, i.Consignee, i.StateName })
                             .GroupBy(i => i.OrderId)
                             .ToDictionary(k => k.Key, v => v.ToList());

                base.Page.Title         = "我的订单";
                base.Model.Orders       = orders;
                base.Model.countNoAudit = CountNoAudit(db);
                return(View["Order", base.Model]);
            };

            Post["/order/express/{orderdetailId}"] = parameters => {
                string orderdetailId = parameters.orderdetailId;
                string express       = Request.Form.express;
                int    i             = db.ExecuteNonQuery("update t_orderdetail set express=@express where id=@orderdetailId",
                                                          new { express = express, orderdetailId = orderdetailId });
                if (i > 0)
                {
                    return(Response.AsJson(new { message = "success" }));
                }
                return(Response.AsJson(new { message = "error" }, Nancy.HttpStatusCode.BadRequest));
            };
        }
Example #15
0
        /// <summary>
        /// 上传图片(自定义保存路径)
        /// </summary>
        /// <param name="uploadPath">保存路径(相对路径)</param>
        /// <param name="postedFile">HttpFile</param>
        /// <param name="picName">图片名称</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static Result SaveImg( String uploadPath, HttpFile postedFile, String picName, int width, int height )
        {
            logger.Info( "uploadPath : " + uploadPath );
            logger.Info( "picName : " + picName );
            Result result = new Result();

            checkUploadPic( postedFile, result );
            if (result.HasErrors) return result;

            String str = PathHelper.Map( uploadPath );
            String str2 = picName + "." + Img.GetImageExt( postedFile.ContentType );
            String filename = Path.Combine( str, str2 );
            try {
                postedFile.SaveAs( filename );
                Img.SaveThumbnail( filename, Img.GetThumbPath( filename ), width, height, SaveThumbnailMode.Cut );
            }
            catch (Exception exception) {
                logger.Error( lang.get( "exPhotoUploadError" ) + ":" + exception.Message );
                result.Add( lang.get( "exPhotoUploadErrorTip" ) );
                return result;
            }
            result.Info = Path.GetFileName( Img.GetThumbPath( filename ) );
            return result;
        }
Example #16
0
 /// <summary>
 /// 保存群组 logo
 /// </summary>
 /// <param name="postedFile"></param>
 /// <param name="groupUrlName"></param>
 /// <returns></returns>
 public static Result SaveGroupLogo(HttpFile postedFile, String groupUrlName)
 {
     return(SaveImg(sys.Path.DiskGroupLogo, postedFile, groupUrlName, config.Instance.Group.LogoWidth, config.Instance.Group.LogoHeight));
 }
Example #17
0
        /// <summary>
        /// 保存上传的文件,如果是图片,则处理缩略图
        /// </summary>
        /// <param name="postedFile"></param>
        /// <returns></returns>
        public static Result SaveFileOrImage( HttpFile postedFile )
        {
            if (postedFile == null) {
                return new Result( lang.get( "exPlsUpload" ) );
            }

            if (Uploader.IsImage( postedFile ))
                return Uploader.SaveImg( postedFile );

            return Uploader.SaveFile( postedFile );
        }
Example #18
0
		public void TestNullName()
		{
            Assert.Throws(typeof(ArgumentNullException), delegate { HttpFile file = new HttpFile(null, null, null); });
		}
Example #19
0
        public void Create()
        {
            int albumId          = ctx.PostInt("PhotoAlbumId");
            int systemCategoryId = ctx.PostInt("SystemCategoryId");

            if (albumId <= 0)
            {
                errors.Add(alang("exAlbumSelect"));
                run(NewPost, albumId);
                return;
            }

            if (systemCategoryId <= 0)
            {
                errors.Add(alang("exSysCategoryRequire"));
                run(NewPost, albumId);
                return;
            }

            if (ctx.GetFiles().Count <= 0)
            {
                errors.Add(alang("exUploadImg"));
                run(NewPost, albumId);
                return;
            }

            List <PhotoPost> imgs = new List <PhotoPost>();

            for (int i = 0; i < ctx.GetFiles().Count; i++)
            {
                HttpFile file = ctx.GetFiles()[i];

                if (file.ContentLength < 10)
                {
                    continue;
                }

                // 发生任何错误,则返回
                Result result = Uploader.SaveImg(file);
                if (result.HasErrors)
                {
                    echo(result.ErrorsHtml);
                    return;
                }

                PhotoPost post = newPost(ctx.Post("Text" + (i + 1)), result.Info.ToString(), albumId, systemCategoryId);
                PhotoApp  app  = ctx.app.obj as PhotoApp;
                postService.CreatePost(post, app);
                imgs.Add(post);
            }

            // 如果没有上传的图片
            if (imgs.Count == 0)
            {
                errors.Add(alang("exUploadImg"));
                run(NewPost, albumId);
                return;
            }

            // 统计
            User user = ctx.owner.obj as User;

            user.Pins = PhotoPost.count("OwnerId=" + user.Id);
            user.update("Pins");

            // feed消息
            addFeedInfo(imgs, albumId);

            echoRedirectPart(lang("opok"), to(new MyController().My), 1);
        }
Example #20
0
 /// <summary>
 /// 保存上传的图片
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Result SaveImg(HttpFile postedFile)
 {
     return(SaveImg(postedFile, ThumbConfig.GetPhotoConfig()));
 }
Example #21
0
 /// <summary>
 /// 判断上传文件是否是图片
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Boolean IsImage(HttpFile postedFile)
 {
     return(IsImage(postedFile.ContentType, postedFile.FileName));
 }
        public void Decode(IRequest message)
        {
            var contentType = message.Headers["Content-Type"];
            //multipart/form-data, boundary=AaB03x
            var boundry = contentType.GetParameter("boundry");

            if (boundry == null)
            {
                throw new FormatException("Missing boundary in content type.");
            }

            var multipart = new HttpMultipart(message.Body, boundry, message.ContentEncoding);

            var form = message.Form;

            /*
             * FileStream stream1 = new FileStream("C:\\temp\\mimebody.tmp", FileMode.Create);
             * byte[] bytes = new byte[stream.Length];
             * stream.Read(bytes, 0, bytes.Length);
             * stream1.Write(bytes, 0, bytes.Length);
             * stream1.Flush();
             * stream1.Close();
             */

            HttpMultipart.Element element;
            while ((element = multipart.ReadNextElement()) != null)
            {
                if (string.IsNullOrEmpty(element.Name))
                {
                    throw new FormatException("Error parsing request. Missing value name.\nElement: " + element);
                }

                if (!string.IsNullOrEmpty(element.Filename))
                {
                    if (string.IsNullOrEmpty(element.ContentType))
                    {
                        throw new FormatException("Error parsing request. Value '" + element.Name +
                                                  "' lacks a content type.");
                    }

                    // Read the file data
                    var buffer = new byte[element.Length];
                    message.Body.Seek(element.Start, SeekOrigin.Begin);
                    message.Body.Read(buffer, 0, (int)element.Length);

                    // Generate a filename
                    var originalFileName = element.Filename;
                    var internetCache    = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

                    // if the internet path doesn't exist, assume mono and /var/tmp
                    var path = string.IsNullOrEmpty(internetCache)
                                   ? Path.Combine("var", "tmp")
                                   : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");

                    element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

                    // If the file exists generate a new filename
                    while (File.Exists(element.Filename))
                    {
                        element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");
                    }

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

                    File.WriteAllBytes(element.Filename, buffer);

                    var file = new HttpFile
                    {
                        Name             = element.Name,
                        OriginalFileName = originalFileName,
                        ContentType      = element.ContentType,
                        TempFileName     = element.Filename
                    };
                    message.Files.Add(file);
                }
                else
                {
                    var buffer = new byte[element.Length];
                    message.Body.Seek(element.Start, SeekOrigin.Begin);
                    message.Body.Read(buffer, 0, (int)element.Length);

                    form.Add(Uri.UnescapeDataString(element.Name), message.ContentEncoding.GetString(buffer));
                }
            }
        }
Example #23
0
        /// <summary>
        /// 上传图片(自定义保存路径),同时生成最小的缩略图
        /// </summary>
        /// <param name="uploadPath">保存路径(相对路径)</param>
        /// <param name="postedFile">HttpFile</param>
        /// <param name="picName">图片名称</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static Result SaveImg( String uploadPath, HttpFile postedFile, String picName, int width, int height, SaveThumbnailMode mode )
        {
            logger.Info( "uploadPath : " + uploadPath );
            logger.Info( "picName : " + picName );
            Result result = new Result();

            CheckUploadPic( postedFile, result );
            if (result.HasErrors) return result;

            String str = PathHelper.Map( uploadPath );
            String str2 = picName + "." + Img.GetImageExt( postedFile.ContentType );
            String filename = Path.Combine( str, str2 );
            try {

                String oldFile = null;
                if (file.Exists( filename )) {
                    oldFile = filename + "." + Guid.NewGuid() + Path.GetExtension( filename );
                    file.Move( filename, oldFile );
                }

                postedFile.SaveAs( filename );

                try {
                    saveThumbImagePrivate( filename, ThumbnailType.Small, width, height, mode );

                    if (strUtil.HasText( oldFile )) {
                        file.Delete( oldFile );
                    }
                }
                catch (OutOfMemoryException ex) {

                    file.Delete( filename );
                    if (strUtil.HasText( oldFile )) {
                        file.Move( oldFile, filename );
                    }

                    String msg = "file format error: " + picName;
                    logger.Error( msg );
                    result.Add( msg );
                    return result;
                }

            }
            catch (Exception exception) {
                logger.Error( lang.get( "exPhotoUploadError" ) + ":" + exception.Message );
                result.Add( lang.get( "exPhotoUploadErrorTip" ) );
                return result;
            }
            result.Info = Path.GetFileName( Img.GetThumbPath( filename ) );
            return result;
        }
Example #24
0
 /// <summary>
 /// 保存上传的图片
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Result SaveImg( HttpFile postedFile )
 {
     return SaveImg( postedFile, ThumbTypes );
 }
Example #25
0
		public void TestNullContent()
		{
		    Assert.Throws(typeof (ArgumentNullException), delegate { HttpFile file = new HttpFile("nun", "nun", null); });
		}
Example #26
0
 /// <summary>
 /// 保存网站 logo
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Result SaveSiteLogo(HttpFile postedFile)
 {
     return(SaveImg(sys.Path.DiskPhoto, postedFile, "logo", config.Instance.Site.LogoWidth, config.Instance.Site.LogoHeight, SaveThumbnailMode.Cut));
 }
Example #27
0
        /// <summary>
        /// Decode body stream
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type header</param>
        /// <param name="encoding">Stream encoding</param>
        /// <returns>Decoded data.</returns>
        /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception>
        /// <exception cref="InternalServerException">Something unexpected failed.</exception>
        /// <exception cref="ArgumentNullException"><c>stream</c> is <c>null</c>.</exception>
        public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (contentType == null)
                throw new ArgumentNullException("contentType");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            //multipart/form-data, boundary=AaB03x
            string boundry = contentType.Parameters["boundary"];
            if (boundry == null)
                throw new FormatException("Missing boundary in content type.");

            var multipart = new HttpMultipart(stream, boundry, encoding);

            var form = new DecodedData();
            /*
            FileStream stream1 = new FileStream("C:\\temp\\mimebody.tmp", FileMode.Create);
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream1.Write(bytes, 0, bytes.Length);
            stream1.Flush();
            stream1.Close();
            */

            HttpMultipart.Element element;
            while ((element = multipart.ReadNextElement()) != null)
            {
                if (string.IsNullOrEmpty(element.Name))
                    throw new FormatException("Error parsing request. Missing value name.\nElement: " + element);

                if (!string.IsNullOrEmpty(element.Filename))
                {
                    if (string.IsNullOrEmpty(element.ContentType))
                        throw new FormatException("Error parsing request. Value '" + element.Name +
                                                  "' lacks a content type.");

                    // Read the file data
                    var buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int) element.Length);

                    // Generate a filename
                    string originalFileName = element.Filename;
                    string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

                    // if the internet path doesn't exist, assume mono and /var/tmp
                    string path = string.IsNullOrEmpty(internetCache)
                                      ? Path.Combine("var", "tmp")
                                      : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");

                    element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

                    // If the file exists generate a new filename
                    while (File.Exists(element.Filename))
                        element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");

                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);

                    File.WriteAllBytes(element.Filename, buffer);

                    var file = new HttpFile
                                   {
                                       Name = element.Name,
                                       OriginalFileName = originalFileName,
                                       ContentType = element.ContentType,
                                       TempFileName = element.Filename
                                   };
                    form.Files.Add(file);
                }
                else
                {
                    var buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int) element.Length);

                    form.Parameters.Add(HttpUtility.UrlDecode(element.Name), encoding.GetString(buffer));
                }
            }

            return form;
        }
Example #28
0
        private static Result upload_private( String uploadPath, HttpFile postedFile, int userId )
        {
            logger.Info( "uploadPath:" + uploadPath + ", userId:" + userId );

            Result result = new Result();

            checkUploadPic( postedFile, result );
            if (result.HasErrors) return result;

            AvatarSaver aSaver = AvatarSaver.New( postedFile );

            return savePicCommon( aSaver, userId, result, uploadPath );
        }
Example #29
0
        /// <summary>
        /// 保存上传的非图片型文件
        /// </summary>
        /// <param name="postedFile"></param>
        /// <returns></returns>
        public static Result SaveFile( HttpFile postedFile )
        {
            Result errors = new Result();

            checkUploadFile( postedFile, errors );
            if (errors.HasErrors) {
                logger.Info( errors.ErrorsText );
                return errors;
            }

            String fileExt = Path.GetExtension( postedFile.FileName );

            String pathName = PathHelper.Map( sys.Path.DiskPhoto );
            String fileName = Img.GetFileName( pathName, fileExt );
            String filenameWithPath = Path.Combine( pathName, fileName );
            try {
                postedFile.SaveAs( filenameWithPath );
            }
            catch (Exception exception) {
                logger.Error( lang.get( "exPhotoUploadError" ) + ":" + exception.Message );
                errors.Add( lang.get( "exPhotoUploadErrorTip" ) );
                return errors;
            }
            errors.Info = fileName.Replace( @"\", "/" );
            return errors;
        }
Example #30
0
 /// <summary>
 /// 保存用户上传的头像
 /// </summary>
 /// <param name="postedFile"></param>
 /// <param name="userId"></param>
 /// <returns></returns>
 public static Result Save( HttpFile postedFile, int userId )
 {
     return upload_private( sys.Path.DiskAvatar, postedFile, userId );
 }
Example #31
0
 /// <summary>
 /// 保存群组 logo
 /// </summary>
 /// <param name="postedFile"></param>
 /// <param name="groupUrlName"></param>
 /// <returns></returns>
 public static Result SaveGroupLogo( HttpFile postedFile, String groupUrlName )
 {
     return SaveImg( sys.Path.DiskGroupLogo, postedFile, groupUrlName, config.Instance.Group.LogoWidth, config.Instance.Group.LogoHeight );
 }
Example #32
0
 /// <summary>
 /// 保存用户上传的头像
 /// </summary>
 /// <param name="postedFile"></param>
 /// <param name="viewerUrl"></param>
 /// <returns></returns>
 public static Result Save( HttpFile postedFile, String viewerUrl )
 {
     return upload_private( sys.Path.DiskAvatar, postedFile, viewerUrl );
 }
Example #33
0
        /// <summary>
        /// 保存上传的图片
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="arrThumbType"></param>
        /// <returns></returns>
        public static Result SaveImg( HttpFile postedFile, ThumbnailType[] arrThumbType )
        {
            Result result = new Result();

            checkUploadPic( postedFile, result );
            if (result.HasErrors) {
                logger.Info( result.ErrorsText );
                return result;
            }

            String pathName = PathHelper.Map( sys.Path.DiskPhoto );
            String photoName = Img.GetPhotoName( pathName, postedFile.ContentType );
            String filename = Path.Combine( pathName, photoName );

            try {
                postedFile.SaveAs( filename );

                foreach (ThumbnailType ttype in arrThumbType) {
                    saveThumbSmall( filename, ttype );
                }

            }
            catch (Exception exception) {
                logger.Error( lang.get( "exPhotoUploadError" ) + ":" + exception.Message );
                result.Add( lang.get( "exPhotoUploadErrorTip" ) );
                return result;
            }
            result.Info = photoName.Replace( @"\", "/" );
            return result;
        }
Example #34
0
 /// <summary>
 /// 判断上传文件是否是图片
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Boolean IsImage( HttpFile postedFile )
 {
     return IsImage( postedFile.ContentType, postedFile.FileName );
 }
Example #35
0
 /// <summary>
 /// 保存网站 logo
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 public static Result SaveSiteLogo( HttpFile postedFile )
 {
     return SaveImg( sys.Path.DiskPhoto, postedFile, "logo", config.Instance.Site.LogoWidth, config.Instance.Site.LogoHeight );
 }
Example #36
0
 public UploadImageBindingModel()
 {
     File = new HttpFile();
 }
Example #37
0
        private static Result upload_private( String uploadPath, HttpFile postedFile, String picName )
        {
            logger.Info( "uploadPath:" + uploadPath + ", picName:" + picName );

            Result result = new Result();

            Uploader.checkUploadPic( postedFile, result );
            if (result.HasErrors) return result;

            String str = PathHelper.Map( uploadPath );
            String str2 = picName + "." + Img.GetImageExt( postedFile.ContentType );
            String srcPath = Path.Combine( str, str2 );
            try {
                postedFile.SaveAs( srcPath );
                saveAvatarThumb( srcPath );
            }
            catch (Exception exception) {
                logger.Error( lang.get( "exPhotoUploadError" ) + ":" + exception.Message );
                result.Add( lang.get( "exPhotoUploadErrorTip" ) );
                return result;
            }

            // 返回的信息是缩略图
            String thumbPath = Img.GetThumbPath( srcPath );
            result.Info = "face/" + Path.GetFileName( thumbPath );
            return result;
        }
Example #38
0
 private string GetMultipartFileHeader(HttpFile file)
 {
     return(string.Format("--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}",
                          FormBoundary, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", Environment.NewLine));
 }
Example #39
0
 public static AvatarSaver New( HttpFile postedFile )
 {
     return new AvatarUploadSaver( postedFile );
 }
Example #40
0
        public OSHttpRequest(HttpListenerContext context)
        {
            _request = context.Request;
            _context = context;

            if (null != _request.Headers["content-encoding"])
                _contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]);
            if (null != _request.Headers["content-type"])
                _contentType = _request.Headers["content-type"];
            _queryString = new NameValueCollection();
            _query = new Hashtable();
            try
            {
                foreach (string item in _request.QueryString.Keys)
                {
                    try
                    {
                        _queryString.Add(item, _request.QueryString[item]);
                        _query[item] = _request.QueryString[item];
                    }
                    catch (InvalidCastException)
                    {
                        MainConsole.Instance.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it",
                                                         item);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                MainConsole.Instance.Error("[OSHttpRequest]: Error parsing querystring");
            }

            if (ContentType != null && ContentType.StartsWith("multipart/form-data"))
            {
                HttpMultipart.Element element;
                var boundry = "";
                var multipart = new HttpMultipart(InputStream, boundry, ContentEncoding ?? Encoding.UTF8);

                while ((element = multipart.ReadNextElement()) != null)
                {
                    if (string.IsNullOrEmpty(element.Name))
                        throw new FormatException("Error parsing request. Missing value name.\nElement: " + element);

                    if (!string.IsNullOrEmpty(element.Filename))
                    {
                        if (string.IsNullOrEmpty(element.ContentType))
                            throw new FormatException("Error parsing request. Value '" + element.Name +
                                                      "' lacks a content type.");

                        // Read the file data
                        var buffer = new byte[element.Length];
                        InputStream.Seek(element.Start, SeekOrigin.Begin);
                        InputStream.Read(buffer, 0, (int) element.Length);

                        // Generate a filename
                        var originalFileName = element.Filename;
                        var internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

                        // if the internet path doesn't exist, assume mono and /var/tmp
                        var path = string.IsNullOrEmpty(internetCache)
                                       ? Path.Combine("var", "tmp")
                                       : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");

                        element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

                        // If the file exists generate a new filename
                        while (File.Exists(element.Filename))
                            element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");

                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);

                        File.WriteAllBytes(element.Filename, buffer);

                        var file = new HttpFile
                                       {
                                           Name = element.Name,
                                           OriginalFileName = originalFileName,
                                           ContentType = element.ContentType,
                                           TempFileName = element.Filename
                                       };
                        Files.Add(element.Name, file);
                    }
                    /*else
                    {
                        var buffer = new byte[element.Length];
                        message.Body.Seek(element.Start, SeekOrigin.Begin);
                        message.Body.Read(buffer, 0, (int)element.Length);

                        form.Add(Uri.UnescapeDataString(element.Name), message.ContentEncoding.GetString(buffer));
                    }*/
                }
            }
        }