使用jquery.form.js文件进行文件上传

本想着文件上传是一件挺简单的事,不过是获取文件地址保存到服务器而已,然而事实并非如此。

我信心满满的写下input type="file",alert input 的value,打开页面选择了张图片,在获取地址的时候,问题出现了,为什么得到的地址是"C:fakepath*.jpg",带着疑惑百度了一圈,原来这是浏览器的安全机制,不让获取文件的物理路径,所以以假路径代替。顿时信心锐减,出师不利啊,看来是轻敌了。

不过百度是个好老师,总能教给你解决问题的办法,一番搜索后,发现了一款上传神器,jquery.form.js,其ajaxSubmit()方法是专门为解决上传问题而生的。

下面就展示一下上传的过程吧。

1.html源码

要上传图片,首先要把file放在form里,异步提交表单,form中需要添加 method="post" enctype="multipart/form-data" 等属性

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
    <form id="uploadform" method="post" enctype="multipart/form-data">
    <input name="uploadimg" id="uploadimg" type="file" style=" 100%" />
    </form>
    <img id="myimg" style=" 80px; height: 80px;border:solid 1px #ccc; border-radius:40px; background-color:#ccc;" />
    
    <script type="text/javascript" src="js/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="js/jquery.form.js"></script>
    <script type="text/javascript" src="js/upload.js"></script>
</body>
</html>
View Code

2.Js文件upload.js代码

$(function () {
    //file内容改变触发表单提交事件
    $("#uploadimg").change(function () {
        $("#uploadform").ajaxSubmit({
            url: "Upload.ashx?action=upload",
            type: "post",
            beforeSubmit: function () {
                $("#myimg").attr("src", "images/loading.gif");
            },
            success: function (url) {
                if (url) {
                    setTimeout(function () {
                        $("#myimg").fadeOut(1000, function () { 
                            $("#myimg").attr("src", url);
                        });
                        $("#myimg").fadeIn(1000);
                    }, 100);
                }
            }
        });
        return false;
    });
});
View Code

3.一般处理程序Upload.ashx代码

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

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

public class Upload : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html"; //设置response的返回值类型text/html,否则会自动加<pre>标签
        string act = context.Request.QueryString["action"].ToString();

        switch (act)
        {
            case "upload":
                ImgUpload(context);
                break;
        }
    }

    /// <summary>
    /// 上传图片至服务器
    /// </summary>
    /// <param name="context"></param>
    public void ImgUpload(HttpContext context)
    {
        List<string> filelist = new List<string>();
        HttpFileCollection files = context.Request.Files;
        for (int i = 0; i < files.Count; i++)
        {
            string filename = System.IO.Path.GetFileName(files[i].FileName);
            filelist.Add(filename);
            string imgpath = "images\upload\";
            string bootpath = HttpRuntime.AppDomainAppPath + imgpath;
            string name = DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + "_" + filename;
            if (!File.Exists(bootpath + name))
            {
                files[i].SaveAs(bootpath + name);
            }
            string localPath = imgpath + name;
            context.Response.Write(localPath);
            context.Response.End();
        }

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

}
View Code

4.附上Demo

此demo是网站,下载后发布在iis或者新建个解决方案把它加进去就可以浏览了。

http://files.cnblogs.com/Jackie-sky/Upload.rar

如果大家在上传方面有其它的解决方法,望不吝赐教。

原文地址:https://www.cnblogs.com/Jackie-sky/p/3678293.html