1. 程式人生 > >ASP.NET 多/單 圖片上傳

ASP.NET 多/單 圖片上傳

前端暫時用layer框架:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="layui/jquery-1.11.0.min.js"></script>

    <link href="layui/css/layui.css" rel="stylesheet" />
    <%--<link href="layui/css/layui.mobile.css" rel="stylesheet" />--%>
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
                <legend>上傳多張圖片</legend>
            </fieldset>

            <div class="layui-upload">
                <button type="button" class="layui-btn" id="test2">多圖片上傳</button>
                <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                    預覽圖:
                    <div class="layui-upload-list" id="demo2"></div>
                </blockquote>
            </div>
        </div>


        <script src="layui/layui.js"></script>
        <script>
            layui.use('upload', function () {
                var $ = layui.jquery , upload = layui.upload;
                //多圖片上傳
                upload.render({
                    elem: '#test2'
                  , url: 'UpLoad.ashx?t=upImg'
                  , multiple: true
                  , before: function (obj) {
                      //預讀本地檔案示例,不支援ie8
                      obj.preview(function (index, file, result) {
                          $('#demo2').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
                      });
                  }
                  , done: function (res) {
                      //上傳完畢   如果是多圖片上傳,則每次上傳完成一個圖片都會呼叫這裡的函式
                      layer.msg(res["msg"]);

                  }, allDone: function (obj) {
                      //當檔案全部被提交後,才觸發
                      //console.log(obj.total); //得到總檔案數
                      //console.log(obj.successful); //請求成功的檔案數
                      //console.log(obj.aborted); //請求失敗的檔案數

                      layer.msg("請求成功的檔案數:" + obj.successful);
                  }
                });
            });
        </script>
    </form>
</body>
</html>

後臺可以是MVC模式,或者普通的一般處理程式ashx模式:

先說MVC模式:

public ActionResult Upload()
        {
            string imgurl = "";
            foreach (string key in Request.Files)
            {
                //這裡只測試上傳第一張圖片file[0]
                HttpPostedFileBase file0 = Request.Files[key];

                //轉換成byte,讀取圖片MIME型別
                Stream stream;
                int size = file0.ContentLength / 1024; //檔案大小KB

                if (size &gt; 1024)
                {
                    return Content(ReturnMsg(Enum_Return.失敗, "圖片不能超過1M:", null));
                }

                byte[] fileByte = new byte[2];//contentLength,這裡我們只讀取檔案長度的前兩位用於判斷就好了,這樣速度比較快,剩下的也用不到。
                stream = file0.InputStream;
                stream.Read(fileByte, 0, 2);//contentLength,還是取前兩位

                //獲取圖片寬和高
                //System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                //int width = image.Width;
                //int height = image.Height;


                string fileFlag = "";
                if (fileByte != null &amp;&amp; fileByte.Length &gt; 0)//圖片資料是否為空
                {
                    fileFlag = fileByte[0].ToString()   fileByte[1].ToString();
                }
                string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//對應的圖片格式jpg,gif,bmp,png
                if (fileTypeStr.Contains(fileFlag))
                {
                    string action = Request["action"];
                    string path = "/uploads/";
                    switch (action)
                    {
                        case "headimage":
                            path    = "headimage/";
                            break;
                        case "blogtype":
                            path    = "blogtype/";
                            break;
                    }
                    string fullpath = path    UserInfo.userID    "/";
                    if (!Directory.Exists(Server.MapPath(fullpath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(fullpath));
                    }


                    Request.Files[key].SaveAs(Server.MapPath(fullpath   Request.Files[key].FileName));
                    imgurl = fullpath    Request.Files[key].FileName;
                }
                else
                {
                    return Content(ReturnMsg(Enum_Return.失敗, "圖片格式不正確:"  fileFlag, null));
                }

                stream.Close();
            }

            return Content(ReturnMsg(Enum_Return.成功, "上傳成功", imgurl));
        }

一般處理程式模式(ashx):

<%@ WebHandler Language="C#" Class="UpLoad" %>

using System;
using System.Web;
using System.Text;
public class UpLoad : IHttpHandler
{

    public void ProcessRequest(HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");

        var t = context.Request.QueryString["t"];
        if(t=="upImg")
        {
            context.Response.ContentType = "application/json";
            HttpPostedFile _upfile = context.Request.Files["File"];
            if (_upfile.ContentLength < 500000)
            {
                if (string.IsNullOrEmpty(_upfile.FileName))
                {
                     context.Response.Write("請上傳圖片");
                }
                string fileFullname = _upfile.FileName;
                string dataName = DateTime.Now.ToString("yyyyMMddhhmmss");
                string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\\")+1);
                string type = fileFullname.Substring(fileFullname.LastIndexOf(".")+1);
                if (type == "bmp" || type == "jpg" || type == "gif" || type == "JPG" || type == "BMP" || type == "GIF")
                {
                    _upfile.SaveAs(HttpContext.Current.Server.MapPath("upload") + "\\" + dataName + "." + type);
                    HttpCookie cookie = new HttpCookie("upload");

                    StringBuilder result = new StringBuilder();
                            result.Append("{");
                            result.Append("\"status\":\"success\",");
                            result.Append("\"msg\":\"上傳成功\"");
                            result.Append("}");
                            this.SetResponse(result.ToString());
                }
                else
                {
                    StringBuilder result = new StringBuilder();
                    result.Append("{");
                    result.Append("\"status\":\"error\",");
                    result.Append("\"msg\":\"僅支援格式:|jpg|gif|bmp|JPEG|GIF|BMP|\"");
                    result.Append("}");
                    this.SetResponse(result.ToString());
                    //context.Response.Write("僅支援格式:|jpg|gif|bmp|JPEG|GIF|BMP|");
                }
            }
            else
            {
                StringBuilder result = new StringBuilder();
                result.Append("{");
                result.Append("\"status\":\"error\",");
                result.Append("\"msg\":\"你的圖片已經超過500K的大小!\"");
                result.Append("}");
                this.SetResponse(result.ToString());
                //context.Response.Write("你的圖片已經超過500K的大小!");
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    public void SetResponse(string str)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write(str);
        HttpContext.Current.Response.End();
    }

}

最後的結果:

相關推薦

ASP.NET / 圖片

前端暫時用layer框架: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html>

ASP.NET MVC 批量圖片(縮圖)

                HttpFileCollectionBase files = Request.Files;                //宣告一個string儲存圖片路徑                //StringBuilder imgs = new

ASP.NET Core WebAPI圖片介面之整合IdentityServer4授權訪問(附原始碼)

點選上方“程式設計師大咖”,選擇“置頂公眾號”關鍵時刻,第一時間送達!來源:依樂祝cnblogs

asp.net幾種開源控件,flash,ajax版,支持文件

控件 custom add into ive select arch asp.net zed 原文發布時間為:2010-03-18 —— 來源於本人的百度文章 [由搬家工具導入]1、AspnetUpload地址

thinkphp 圖片 圖片

http json 多圖片上傳 模板 tar err ram mbo htm 不管是單圖片上傳還是多圖片上傳都必須要引用這兩個js 下載地址 鏈接:http://pan.baidu.com/s/1eStkUt0 密碼:asvo <script src="Public

asp.net core 通過ajax圖片及wangEditor圖片

images use class multi jquery 開始 load als org asp.net core 通過ajax上傳圖片 .net core前端代碼,因為是通過ajax調用,首先要保證ajax能調用後臺代碼,具體參見上一篇.net core 使用ajax

asp.net簡單例項——同時個檔案

     之前在網站上看到的一些上傳檔案的功能,感覺還是蠻方便的,這次自己利用asp.net中的HttpFileCollection類做了一個簡單的例子。廢話不多說,下面看操作。     首先,新增一個新的web窗體,在窗體上直接拖拽這幾個控制元件:一個Panel作為容器、

使用plupload.js實現頁面例項圖片

工作中經常會遇到單頁面多個上傳模組的功能,比如身份證正反面。使用plupload.js可以非常簡單的實現這個功能。 github下載地址 https://github.com/moxiecode/plupload/tree/master/js 新建plupload.htm

PHP+jQuery+Ajax圖片

近日寫的一個銷售管理系統中,需要使用者上傳產品的圖片,找了好多外掛,用起來都挺麻煩的而且還不好改,最後找到一篇用php和ajax做圖片上傳的,感覺程式碼挺簡單的而且改起來很容易,轉發到此處與各位分享一下: 我們在本文中用到一個Ajax表單提交外掛:jqery.

Bootstrap框架---krajee外掛fileinput--最好用的檔案元件----圖片互動方式三(推薦)

我們在前一章已經實現了 Bootstrap框架---Uploadify外掛----多張圖片上傳互動方式二 。本章主要關注單多張圖片上傳在Bootstrap框架中的佈局和實現。我們在之前的文章中已經在SpringMVC基礎框架的基礎上應用了BootStrap的後臺框架,在此基礎

asp.net 中一次個檔案

看到一篇老外的文章,說在asp.net 中,如何先讓使用者把要上傳的檔案都選好了,然後一次上傳,今小結如下首先在頁面加一個上傳檔案控制元件,一個“attach"按鈕,一個listbox,用來存放等待上傳的檔名,一個"UPLOAD"按鈕,一個”刪除按鈕 <form

C# asp.net實現文件

function asp.net visual 開發 null 前端代碼: 使用visual studio開發實現文件上傳 前端頁面代碼: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.as

.net 文件

use tde com get pub 獲取文件 def eas style 版權聲明:本文為博主原創文章,未經博主允許不得轉載。 1.頁面 <head runat="server"> <title>上傳文件</title>

微信小程序圖片

let type 程序 nal pre 圖片 知識 地址 bug 微信小程序上傳圖片每次只能上傳一張,所有很多朋友就會問想要多張圖片上傳怎麽辦? 首先,我們來看一看wx.chooseImage(object)和wx.uploadFile(OBJECT)這兩個個api

(轉)ASP.NET(C#)FileUpload實現限定類型和大小的文件到服務器

web 環境 posted using 結果 ring event run ont 上傳文件有兩個主要的目的地,一個是服務器,另一個是數據庫,ASP.NET內置了FileUpload這個上傳控件,文本框顯示用戶選擇的文件的全名. 其屬性主要包括: ContenLength:

ASP.NET Core文件與下載(多種方式)

long filepath guid sum tool 是我 ajax 控件 host 前段時間項目上線,實在太忙,最近終於開始可以研究研究ASP.NET Core了. 打算寫個系列,但是還沒想好目錄,今天先來一篇,後面在整理吧. ASP.NET Core 2.0

圖片

i++ pts ugc bus enc bbr aes num jdb 圖片上傳單個圖片樣式 上面的效果 所使用的js 點擊文件上傳之後進行新增保存的時候,先上傳圖片至文件夾,之後進行數據保存, controller後臺實現代碼這裏是上傳,新增保存的方法就不寫了

ASP.NET CORE的H5

圖片 tle core asp asp.net 修改 分享 c代碼 net 做的CORE項目中用到H5上傳,把以前的MVC代碼復制過來得修改一下才能用在.NET CORE中

ASP.NET Core文件、下載與刪除

隨機 sting control 擴展 isa 上傳文件 result load() tip 首先我們需要創建一個form表單如下: <form method="post" enctype="multipart/form-data" asp-controller=

asp.net編輯html文章報錯[檢測到潛在危險]

frame 文章 ati 編輯 img 報錯 inf 上傳 ima net framework2.0升級成4.0後,上傳文章報錯 解決方案 在web.config裏添加<system.web><httpRuntime requestValidati