zoukankan      html  css  js  c++  java
  • 文件上传 简单处理 .

    Html:head部分 js判断:

    View Code
    <script>
    function Check_FileType()
    {
       var str=document.getElementById("FileUpload1").value;  //获取id为FileUpload1的值
        var pos = str.lastIndexOf(".");                        //字符处理取" ."的后缀
        var lastname = str.substring(pos,str.length)           //截取
        if (lastname.toLowerCase()!=".jpg" && lastname.toLowerCase()!=".gif")
        {
         alert("您上传的文件类型为"+lastname+",图片必须为.jpg,.gif类型");
         return false;       
      }
     else 
      {
       return true;
       }
    } 
     </script> 

    页面源代码:

    View Code
     <asp:FileUpload ID="FileUpload1" runat="server"  />
    <asp:Button ID="bt_upload" runat="server"   OnClientClick="return Check_FileType()"  OnClick="bt_upload_Click" Text="上传" />

    cs代码:

    View Code
    try
        {
            if (FileUpload1.PostedFile.FileName == "")
              {
                   this.lb_info.Text = "请选择文件!";
               }
              else
                {
                   string filepath = FileUpload1.PostedFile.FileName;                                           
                   string filename = filepath.Substring(filepath.LastIndexOf("\\")+1);
                   string serverpath = Server.MapPath( "images/")+Guid.NewGuid() + filename; //这里加了guid不用担心插入同一张图片报错
                     FileUpload1.PostedFile.SaveAs(serverpath);
                   this.lb_info.Text = "上传成功!";
                }
          }
         catch (Exception ex)
          {
              throw ex;  
           }
    
     
    或者:
           string urlpath = string.Empty;
          string url = this.fileupload.PostedFile.FileName;   //上传时的文件路径
           if (fileupload.HasFile)
            {
              string saveurl = AppDomain.CurrentDomain.BaseDirectory + "QuestionMsg\\QuestionFlowMsg\\UplodExcel\\";  //保存路径
                string filename = url.Substring(url.LastIndexOf('\\') + 1);   //保存文件名
                 if (!Directory.Exists(saveurl))
                   Directory.CreateDirectory(saveurl);
                 this.fileupload.PostedFile.SaveAs(saveurl + filename);
                  urlpath = saveurl + filename;
            }
    
    或者:
     try
            {
                if (Fupload.PostedFile.FileName=="")
                {
                   msg = "请选择文件!";
                }
                else
                {
                    string filepath = Fupload.PostedFile.FileName;
                    string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                    string serverpath = Server.MapPath("images/") + Guid.NewGuid() + filename;
                    string fileName ="F:\\Auto\\images\\";
                    if (!Directory.Exists(fileName))
                    {
                        Directory.CreateDirectory(fileName);
                        if (!Directory.Exists(fileName))
                            return;
                    }
                    Fupload.PostedFile.SaveAs(serverpath);
                    msg = "上传成功!";
    
                }
            }
            catch (Exception ex)
            {
                throw ex; 
    
            }
        }

    一般处理程序 接受文件post

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using SMS.Common;
    
    namespace SMS.FileUpload
    {
        /// <summary>
        /// FileUpload 的摘要说明
        /// </summary>
        public class FileUpload : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.Buffer = true;
                context.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(0);
                context.Response.AddHeader("Pragma", "No-Cache");
                context.Response.Expires = 0;
                //context.Response.ContentType = "text/plain";
                //context.Response.Charset = "utf-8";
    
                string action = context.Request["action"];                          //获取操作类型
                switch (action)
                {
                    default: ResponseFileUpload(context); break;
                }
            }
    
    
            private void ResponseFileUpload(HttpContext context)
            {
                var path = "";
                var fileName = "";
                FileStream fstream = null;
                try
                {
                    StreamReader stw = new StreamReader(HttpContext.Current.Request.InputStream);
                    string PostData = stw.ReadToEnd();
    
                    var p = DynamicJson.Parse(PostData.ToString());
    
                    var content = p.Content;
                  //  fileName = p.Name;
    
                    //var content =context.Request["Content"];
                    //fileName = context.Request["Name"];
                    string[] Extension = p.Name.Split('.');
    
                    fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + Extension[1];
    
                    path = HttpContext.Current.Server.MapPath(string.Format("../UserFile/{0}", DateTime.Now.ToString("yyyyMMdd")));
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    if (content!=null)
                    {
                        byte[] imageBytes = Convert.FromBase64String(content);
                        fstream = File.Create(path +"/"+ fileName, imageBytes.Length);
                        fstream.Write(imageBytes, 0, imageBytes.Length);
                        fstream.Close();
                    }
                    ResponseMsg(context, string.Format("UserFile/{0}/{1}", DateTime.Now.ToString("yyyyMMdd"), fileName));
                }
                catch 
                {
                    context.Response.Write("{ \"result\":-1}");
                    fstream.Close();
                }
            }
    
            public void ResponseMsg(HttpContext context, string path)
            {
                context.Response.Write("{ \"result\":\"" + path + "\"}");
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
  • 相关阅读:
    Java控制台五子棋编码学习
    Java Web基础
    JavaScript Unit Test with Mocha
    Cross-browser Testing Tool
    GRIDVIEW 控件
    C# .net ACCESS 网页增删改查 --留言板
    在一般处理文件中访问Session需要添加IRequiresSessionState(转载)
    win7 IIS7 发布网站 出现 "处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误"
    http://www.cnblogs.com/hanshuhe/archive/2012/08/30/vss.html
    win 7 配置 IIS
  • 原文地址:https://www.cnblogs.com/y112102/p/2563984.html
Copyright © 2011-2022 走看看