1. 程式人生 > >Asp.net使用form上傳檔案

Asp.net使用form上傳檔案

1 – 頁面程式碼: uploadfile.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <form name="form" method="post" action="uploadfile.ashx" target="returnifr" enctype="multipart/form-data" >
        <div>
<label>姓名:</label> <input type="text" name="name" value="" /> </div> <div> <label>手機:</label> <input type="text" name="phone" value="" /> </div> <div> <label
>
郵箱:</label> <input type="text" name="email" value="" /> </div> <div> <label>檔案:</label> <input type="file" name="file" value="" /> </div> <div> <input type="submit" name
="submit" value="提交" />
</div> </form> <iframe name="returnifr" id="returnifr" style="display: none;"></iframe> </body> </html>

說明:

  • form上傳檔案一定要用 enctype=”multipart/form-data”:不對字元編碼。當使用有檔案上傳控制元件的表單時,該值是必需的。
  • 上傳檔案用post
  • 後臺context.Response.Write()會返回新的頁面,因此在頁面頁面設定隱藏的iframe防止跳轉

2 – 後臺程式碼 uploadfile.ashx

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace WebApplication2
{
    public class uploadfile : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //獲取前端傳遞的引數
            HttpServerUtility server = context.Server;
            string filename = "";
            string filepath = "";
            string savefile = "";
            string name = "";
            string phone = "";
            string email = "";            
            try
            {
                //判斷檔案型別,更多型別見http://tool.oschina.net/commons
                List<string> fileType = new List<string>() { "application/msword", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain" };
                HttpPostedFile file = context.Request.Files[0];
                //驗證檔案型別和大小
                if (!fileType.Contains(file.ContentType) || file.ContentLength >= 10000000)
                {
                    throw new Exception("檔案型別錯誤");
                }
                var param = context.Request.Params;
                name = param["name"];
                phone = param["phone"];
                email = param["email"];
                //檢查資料格式
                if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(email) || !checkName(name) || !checkPhone(phone) || !checkEmail(email))
                {
                    throw new Exception("資料格式錯誤");
                }
                if (file.ContentLength > 0)
                {
                    //IE傳完成路徑,chrome傳檔名
                    string[] str = file.FileName.Split('\\');
                    filename = str[str.Length - 1];
                    if (filename.Length > 100)
                    {
                        filename = filename.Substring(0, 100);
                    }
                    string time = DateTime.Now.ToString("yyyyMMdd");
                    filepath = server.MapPath("~\\file\\") + time;
                    if (Directory.Exists(filepath) == false)
                    {
                        Directory.CreateDirectory(filepath);
                    }
                    //儲存檔案
                    savefile = filepath + "\\" + name + "-" + phone + "-" + email + "-" + filename;
                    file.SaveAs(savefile);
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write("success");
            }
            catch (Exception e)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(e.Message);
                context.Response.End();
            }
        }
        //驗證姓名中文、郵箱、手機格式
        public static bool checkEmail(string str_email)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(str_email.Trim(), @"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$");
        }
        public static bool checkPhone(string str_phone)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(str_phone.Trim(), @"^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$");
        }
        public static bool checkName(string str_name)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(str_name.Trim(), @"^[\u4e00-\u9fa5]+$");
        } 
    }
}

3 – Asp.net檔案上傳大小限制

在Web.config中,<system.web>...</system.web>中間新增<httpRuntime maxRequestLength="20480" executionTimeout="240"/>,單位kb和s

4 – input[‘file’]樣式修改
常見的樣式修改用新樣式覆蓋在input,input透明度設定為0

<div>
    <label>檔案:</label>
    <span style="position:relative;width:60px;height:25px;">
        <span class="bt" style="position:absolute;" >瀏覽</span>
        <input type="file" name="file" value="" style="width:60px;opacity:0; "/>
    </span>
</div>

<style>
    .bt
    {
        background-color: #4CAF50; /* Green */
        border: none;
        color: white;s
        width:60px;
        height:25px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
    }
</style>