一般处理程序获取Layui上传的图片

asp.net利用一般处理程序获取用户上传的图片,上传图片利用的layui

 

前台页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="CacheTest.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    //需要引入layui需要的css和js文件
    <link href="layui/css/layui.css" rel="stylesheet" />
    <script src="layui/layui.js"></script>
    <script>
        layui.use('upload', function () {
            var $ = layui.jquery, upload = layui.upload;

            //普通图片上传
            var uploadInst = upload.render({
                elem: '#test1',
                url: '一般处理程序',
                auto: false,
                BindAction: "#按钮",
                choose: function(ohj) {//点击上传前预览
                    //预读本地文件示例,不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#demo1').attr('src', result); //图片链接(base64)
                    });
                },
                before: function (obj) {
                    //预读本地文件示例,不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#demo1').attr('src', result); //图片链接(base64)
                    });
                },
                done: function (res) {//完成事件
                    //如果上传失败
                    if (res.code > 0) {
                        return layer.msg('上传失败');
                    }
                    //上传成功
                },
                error: function () {
                    //演示失败状态,并实现重传
                    var demoText = $('#demoText');
                    demoText.html(
                        '<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click',
                        function () {
                            uploadInst.upload();
                        });
                }
            });
        })
    </script>
</head>
<body>
    <form id="form1">
        <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="test1">上传图片</button>
            <div class="layui-upload-list">
                <img class="layui-upload-img" id="demo1" style="width:200px">
                <p id="demoText"></p>
            </div>
        </div>
    </form>
</body>
</html>

一般处理程序 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        string fileNameNo = "";
        string DirectoryName = "";
        string Extension = "";
        string fileName = "";
        string fullPath = "";
        string uploadDown = "";
        string savePath = "";
        string netPath = "";
        string parm = "";
        StringBuilder msg = new StringBuilder();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string physicalPath = System.Web.HttpContext.Current.Server.MapPath("/Upload/");
            //parm = context.Request.QueryString["id"].ToString();
            HttpFileCollection hfc = context.Request.Files;

            if (hfc.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0];
                if (hpf.ContentLength > 0)
                {
                    //获取文件名和扩展名 
                    fileNameNo = Path.GetFileName(hpf.FileName);
                    //获取文件所在目录 
                    DirectoryName = Path.GetDirectoryName(hpf.FileName);
                    //获取扩展名 
                    Extension = Path.GetExtension(hpf.FileName);
                    if (AvailableFileType(Extension)) //文件格式符合
                    {
                        if (hpf.ContentLength <= 1024 * 1024 * 4) //文件大小符合
                        {

                            //获取文件名(不包括扩展名)
                            fileName = Path.GetFileNameWithoutExtension(hpf.FileName);
                            string newFileName = Guid.NewGuid().ToString().Replace("-", "") + Extension;
                            uploadDown = physicalPath + newFileName;
                            netPath = "../upload/" + newFileName;
                            savePath = Path.Combine(physicalPath, newFileName);
                            hpf.SaveAs(savePath);
                            msg.Append(
                                "{\"isok\":\"true\",\"username\":\"\",\"createtime\":\"\",\"message\":\"上传成功\",\"sourcefilename\":\"" +
                                context.Request.RawUrl + "\",\"netfilename\":\"" + netPath + "\",\"fileid\":\"" +
                                newFileName + "\"}");
                            context.Response.Write(msg.ToString());
                            //获取文件的绝对路径 
                            //string fullPath = Path.GetFullPath(FileUploadImg.PostedFile.FileName);
                            ////获取文件所在地分区 
                            //string PathRoot = Path.GetPathRoot(FileUploadImg.PostedFile.FileName); 
                        }
                        else
                        {
                            msg.Append(
                                "{\"isok\":\"false\",\"username\":\"\",\"createtime\":\"\",\"message\":\"上传失败,上传文档不能大于4MB!\",\"sourcefilename\":\"\",\"netfilename\":\"\",\"fileid\":\"\"}");
                            context.Response.Write(msg.ToString());
                        }
                    }
                    else //文件格式不符合
                    {
                        msg.Append(
                            "{\"isok\":\"false\",\"username\":\"\",\"createtime\":\"\",\"message\":\"文件格式不支持,支持bmp,jpg,gif,png,rar,zip,doc,xls,docx,xlsx格式的上传!\",\"sourcefilename\":\"\",\"netfilename\":\"\",\"fileid\":\"\"}");
                        context.Response.Write(msg.ToString());
                    }
                }
                else
                {
                    msg.Append(
                        "{\"isok\":\"false\",\"username\":\"\",\"createtime\":\"\",\"message\":\"请选择上传的文件\",\"sourcefilename\":\"\",\"netfilename\":\"\"}");
                    context.Response.Write(msg.ToString());
                }
            }
            else
            {
                msg.Append(
                    "{\"isok\":\"false\",\"username\":\"\",\"createtime\":\"\",\"message\":\"请选择上传的文件\",\"sourcefilename\":\"\",\"netfilename\":\"\"}");
                context.Response.Write(msg.ToString());
            }
        }
        public bool AvailableFileType(string temp)
        {
            string[] TypeBag = { ".bmp", ".jpg", ".gif", ".png", ".rar", ".zip", ".doc", ".xls", ".docx", ".xlsx" };
            if (Array.IndexOf(TypeBag, temp) == -1) return false;
            else return true;
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

posted @ 2018-04-27 10:45  IcareU  阅读(2035)  评论(0编辑  收藏  举报