.NET图片上传接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36169781/article/details/86585055

uploadIMG.ashx

<%@ WebHandler Language="C#" Class="uploadIMG" %>
using System;
using System.Web;
using System.IO; 
using System.Drawing;
using System.Drawing.Imaging;

public class uploadIMG : IHttpHandler {
    
    public void ProcessRequest(HttpContext context)
    {
        string end = "{\"code\": 1,\"msg\": \"服务器故障\",\"data\": {\"src\": \"\"}}"; //State

         HttpPostedFile file = context.Request.Files[0]; //获取选中文件
        Stream stream = file.InputStream;    

        Image img = Image.FromStream(stream);//将流中的图片转换为Image图片对象
 
        Random ran = new Random((int)DateTime.Now.Ticks);

        string serverPath = "/imgUploads/" + DateTime.Now.ToString("yyyyMMddhhmmssms") + ran.Next(99999) + ".jpg";//文件保存位置及命名

        string path = context.Server.MapPath(serverPath);
 
        try
        {
            img.Save(path, ImageFormat.Jpeg);
 
            
            end = "{\"code\": 0,\"msg\": \"成功\",\"data\": {\"src\": \"" + serverPath + "\"}}";
        }
        catch { }
 
        context.Response.Write(end);//输出结果
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

upoadImg.js

function uploadIMG() {
//使用了Layui
    layui.use(['element', 'layer','upload'], function () {
        var layer = layui.layer
            , element = layui.element
            , upload = layui.upload;
        upload.render({
            elem: '#upPic'
            , url: 'uploadIMG.ashx'//接口地址
            , accept: 'images'
            , done: function (res, index, upload) { //上传后的回调
                layer.msg("上传成功!");
            }
            //,accept: 'file' //允许上传的文件类型
            //,size: 50 //最大允许上传的文件大小
            //,……
        });
    });
}

猜你喜欢

转载自blog.csdn.net/qq_36169781/article/details/86585055