图片 音频 视频上传

上传文件使用ashx来处理,该部分代码可以处理任何上传的文件保存到制定文件夹

int LocationID = 0;//图片关联外键
        string description = null;//图片描述
        int success = 1;
        public void ProcessRequest(HttpContext context)
        {

            context.Response.ContentType = "text/plain";
            context.Response.Charset = "UTF-8";
            HttpFileCollection uploadedFiles = context.Request.Files;

            Loger.Debug("用户进入接口");
            try
            {
                if (context.Request["locationid"] != null)
                {
                    LocationID = Convert.ToInt32(context.Request["locationid"]);
                }
                if (context.Request["description"] != null)
                {
                    description = Convert.ToString(context.Request["description"]);
                }
                Loger.Debug(string.Format("用户上传参数:LocationID :{0},description :{1}", LocationID, description));
                for (int j = 0; j < uploadedFiles.Count; j++)
                {
                    HttpPostedFile F1 = uploadedFiles[j];

                    Loger.Debug(string.Format("用户上传附件数量:{0}", F1.ContentLength));
                    if (uploadedFiles[j] != null && F1.ContentLength > 0)
                    {
                        string filepath = DateTime.Now.ToString("yyyyMMdd");
                        //是服务器绝对路径 列如C:\Inetpub\wwwroot\DamangeWebService
                        string path = ConfigurationSettings.AppSettings["Img"].ToString() + "/" + filepath + "/";
                        Loger.Debug(string.Format("图片上传路径是:{0}", path));

                        CommonFunc.FolderCreate(path);

                        for (int i = 0; i < uploadedFiles.Count; i++)
                        {
                            HttpPostedFile F = uploadedFiles[i];

                            if (uploadedFiles[i] != null && F.ContentLength > 0)
                            {
                                //得到上传文件的长度
                                int upFileLength = F.ContentLength;
                                //Loger.Debug("upFileLength==>" + upFileLength);
                                //得到上传文件的客户端MIME类型
                                string contentType = F.ContentType;
                                byte[] FileArray = new Byte[upFileLength];
                                Stream fileStream = F.InputStream;
                                fileStream.Read(FileArray, 0, upFileLength);
                                int index = F.FileName.LastIndexOf('.');
                                string filename = F.FileName.Replace(F.FileName.Substring(0, index), Guid.NewGuid().ToString());

                                string pathUrl = path + filename;
                                F.SaveAs(pathUrl);
                                Loger.Debug(string.Format("图片最终保存路径是:{0}", pathUrl));
                              
                                success = SaveimageToBase(F.ContentLength, pathUrl, F.InputStream);
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                success = 0;
                Loger.Debug(string.Format("异常原因:{0}", ex.ToString()));
            }
            finally
            {
                HttpContext.Current.ApplicationInstance.CompleteRequest();
                Loger.Debug("success状态===》" + success);
                context.Response.Write(success);
                context.Response.Flush();
                context.Response.End();
            }
View Code

由于上传的是图片,直接保存 到文件夹里面。当然也可以顺便把压缩过的图片保存到数据库

 /// <summary>
        /// 保存图片到数据库
        /// </summary>
        /// <param name="length">图片大小</param>
        /// <param name="fileName">名称</param>
        /// <param name="stream">图片文件流</param>
        /// <returns></returns>
        private int SaveimageToBase(double length, string fileName, Stream stream)
        {

            int success = 1;
            System.Drawing.Image original_image = null;
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            original_image = System.Drawing.Image.FromStream(stream);
            int width = original_image.Width;
            int height = original_image.Height;
            int target_width = 400;
            int target_height = 300;
            int new_width, new_height;
            try
            {
                float target_ratio = (float)target_width / (float)target_height;
                float image_ratio = (float)width / (float)height;

                if (target_ratio > image_ratio)
                {
                    new_height = target_height;
                    new_width = (int)Math.Floor(image_ratio * (float)target_height);
                }
                else
                {
                    new_height = (int)Math.Floor((float)target_width / image_ratio);
                    new_width = target_width;
                }

                new_width = new_width > target_width ? target_width : new_width;
                new_height = new_height > target_height ? target_height : new_height;

                final_image = new System.Drawing.Bitmap(target_width, target_height);
                graphic = System.Drawing.Graphics.FromImage(final_image);
                graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height));
                int paste_x = (target_width - new_width) / 2;
                int paste_y = (target_height - new_height) / 2;
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);
                MemoryStream ms = new MemoryStream();
                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                // DisasterImageSound 这个是保存图片的对象
                DisasterImageSound Model = new DisasterImageSound();
                Model.Data = ms.GetBuffer();
                Model.LocationID = Convert.ToInt32(LocationID);
                Model.FileSize = length;
                Model.ContentType = fileName;
                Model.Description = description;
                new BLL.DisasterImageSound().Add(Model);
            }
            catch (Exception ex)
            {
                success = 0;
                Loger.Debug(string.Format("SaveimageToBase异常.异常愿意:{0}", ex.ToString()));
            }
            return success;
        }
View Code

 

调用ashx 方法 url可以添加各种参数。同理可以在ashx可以获取到 ,url 是ashx部署的地址,Server.MapPath("TMp/" + filename) 这个是文件

  string url = ConfigurationSettings.AppSettings["ImgUrl"].ToString();
                    System.Net.WebClient myWebClient = new System.Net.WebClient();
                    myWebClient.UploadFile(url, "POST", Server.MapPath("TMp/" + filename)); 

 

 

 

posted @ 2013-07-11 12:25  骑士归来  阅读(487)  评论(0编辑  收藏  举报