如何同时提交图片和表单数据(图片提交到服务器 数据提交到数据库)

时间:2022-01-26 07:06:33

//一般处理文件
  public void ProcessRequest(HttpContext context)
        {
           
              
                 HttpFileCollection collection = context.Request.Files;
                 HttpPostedFile  file = collection[0];
                 string  fileName = file.FileName;
                 file.SaveAs("//192.168.1.3/pic/" + fileName);
                 context.Response.ContentType = "text/plain";
          
         
        }




 function AcceptClick() {
 
        var options = {
            type: "get",
            dataType: 'text',
            url: '~/jieshou.ashx',
            cache: false,
            success: function () {
                alert("上传成功!");
            }
        };
 
  
        $('#form2').ajaxSubmit(options);



<form name="fileup" id="form2" method="get" action="~/jieshou.ashx" enctype="multipart/form-data">
    <table>
        <tr>
            <th class='formTitle'>选择文件:</th>
            <td class='formValue'>
                <input id="file" type="file" name="fileup" />
            </td>
        </tr>
    </table>
</form>





3 个解决方案

#1


图片和数据都提交到后台,然后后台把图片提交到图片服务器,把数据存储到数据服务器

#3


测试
HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#upload").click(function () {
                $("#imgWait").show();
                var formData = new FormData();
                formData.append("myfile", document.getElementById("file1").files[0]);
                $.ajax({
                    url: "upload.ashx",
                    type: "POST",
                    data: formData,
                    /**
                    *必须false才会自动加上正确的Content-Type
                    */
                    contentType: false,
                    /**
                    * 必须false才会避开jQuery对 formdata 的默认处理
                    * XMLHttpRequest会对 formdata 进行正确的处理
                    */
                    processData: false,
                    success: function (data) {
                        if (data.status == "true") {
                            alert("上传成功!");
                        }
                        if (data.status == "error") {
                            alert(data.msg);
                        }
                    },
                    error: function () {
                        alert("上传失败!");
                        $("#imgWait").hide();
                    }
                });
            });
        });
    </script>
</head>
<body>
    选择文件:<input type="file" id="file1" /><br />
    <input type="button" id="upload" value="上传" />
    <img src="wait.gif" style="display:none" id="imgWait" />
</body>
</html>


ASHX

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

using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Web.Script.Serialization;

public class Upload : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        if (context.Request.Files.Count > 0)
        {
            HttpPostedFile file1 = context.Request.Files["myfile"];
            helper.uploadImg(file1, "~/UploadFile/");  //这里引用的是上面封装的方法
            WriteJson(context.Response, "true", "");
        }
        else
        {
            WriteJson(context.Response, "error", "请选择要上传的文件");
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    public static void WriteJson(HttpResponse response,string status1, string msg1, object data1 = null)
    {
        response.ContentType = "application/json";
        var obj = new { status = status1, msg = msg1, data = data1 };
        string json = new JavaScriptSerializer().Serialize(obj);
        response.Write(json);
    }
}

public class helper
{
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="file">通过form表达提交的文件</param>
    /// <param name="virpath">文件要保存的虚拟路径</param>
    public static void uploadImg(HttpPostedFile file, string virpath)
    {
        if (file.ContentLength > 1024 * 1024 * 4)
        {
            throw new Exception("文件不能大于4M");
        }
        string imgtype = Path.GetExtension(file.FileName);
        if (imgtype != ".jpg" && imgtype != ".jpeg")  //图片类型进行限制
        {
            throw new Exception("请上传jpg或JPEG图片");
        }
        using (Image img = Bitmap.FromStream(file.InputStream))
        {
            string savepath = HttpContext.Current.Server.MapPath(virpath + file.FileName);
            img.Save(savepath);
        }
    }
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="file">通过form表达提交的文件</param>
    /// <param name="virpath">文件要保存的虚拟路径</param>
    public static void uploadFile(HttpPostedFile file, string virpath)
    {
        if (file.ContentLength > 1024 * 1024 * 6)
        {
            throw new Exception("文件不能大于6M");
        }
        string imgtype = Path.GetExtension(file.FileName);
        //imgtype对上传的文件进行限制
        if (imgtype != ".zip" && imgtype != ".mp3")
        {
            throw new Exception("只允许上传zip、rar....文件");
        }
        string dirFullPath = HttpContext.Current.Server.MapPath(virpath);
        if (!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹
        {
            Directory.CreateDirectory(dirFullPath);
        }
        file.SaveAs(dirFullPath + file.FileName);
    }
}

#1


图片和数据都提交到后台,然后后台把图片提交到图片服务器,把数据存储到数据服务器

#2


#3


测试
HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#upload").click(function () {
                $("#imgWait").show();
                var formData = new FormData();
                formData.append("myfile", document.getElementById("file1").files[0]);
                $.ajax({
                    url: "upload.ashx",
                    type: "POST",
                    data: formData,
                    /**
                    *必须false才会自动加上正确的Content-Type
                    */
                    contentType: false,
                    /**
                    * 必须false才会避开jQuery对 formdata 的默认处理
                    * XMLHttpRequest会对 formdata 进行正确的处理
                    */
                    processData: false,
                    success: function (data) {
                        if (data.status == "true") {
                            alert("上传成功!");
                        }
                        if (data.status == "error") {
                            alert(data.msg);
                        }
                    },
                    error: function () {
                        alert("上传失败!");
                        $("#imgWait").hide();
                    }
                });
            });
        });
    </script>
</head>
<body>
    选择文件:<input type="file" id="file1" /><br />
    <input type="button" id="upload" value="上传" />
    <img src="wait.gif" style="display:none" id="imgWait" />
</body>
</html>


ASHX

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

using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Web.Script.Serialization;

public class Upload : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        if (context.Request.Files.Count > 0)
        {
            HttpPostedFile file1 = context.Request.Files["myfile"];
            helper.uploadImg(file1, "~/UploadFile/");  //这里引用的是上面封装的方法
            WriteJson(context.Response, "true", "");
        }
        else
        {
            WriteJson(context.Response, "error", "请选择要上传的文件");
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    public static void WriteJson(HttpResponse response,string status1, string msg1, object data1 = null)
    {
        response.ContentType = "application/json";
        var obj = new { status = status1, msg = msg1, data = data1 };
        string json = new JavaScriptSerializer().Serialize(obj);
        response.Write(json);
    }
}

public class helper
{
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="file">通过form表达提交的文件</param>
    /// <param name="virpath">文件要保存的虚拟路径</param>
    public static void uploadImg(HttpPostedFile file, string virpath)
    {
        if (file.ContentLength > 1024 * 1024 * 4)
        {
            throw new Exception("文件不能大于4M");
        }
        string imgtype = Path.GetExtension(file.FileName);
        if (imgtype != ".jpg" && imgtype != ".jpeg")  //图片类型进行限制
        {
            throw new Exception("请上传jpg或JPEG图片");
        }
        using (Image img = Bitmap.FromStream(file.InputStream))
        {
            string savepath = HttpContext.Current.Server.MapPath(virpath + file.FileName);
            img.Save(savepath);
        }
    }
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="file">通过form表达提交的文件</param>
    /// <param name="virpath">文件要保存的虚拟路径</param>
    public static void uploadFile(HttpPostedFile file, string virpath)
    {
        if (file.ContentLength > 1024 * 1024 * 6)
        {
            throw new Exception("文件不能大于6M");
        }
        string imgtype = Path.GetExtension(file.FileName);
        //imgtype对上传的文件进行限制
        if (imgtype != ".zip" && imgtype != ".mp3")
        {
            throw new Exception("只允许上传zip、rar....文件");
        }
        string dirFullPath = HttpContext.Current.Server.MapPath(virpath);
        if (!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹
        {
            Directory.CreateDirectory(dirFullPath);
        }
        file.SaveAs(dirFullPath + file.FileName);
    }
}