javascript - 使用 ajax 和 asp.net 将文件保存到 SQL Server 数据库

标签 javascript jquery asp.net ajax web-services

我已经使用 ajax 和 asp.net 将文件插入到我的 sqlserver2012 数据库中,但我得到如下所示的错误结果:
我的错误 本地主机:6446 syas: [对象对象]

在 HTML 和 ajax jquery 中

$(document).ready(function () {
	$('#btn_upload').click(function () {
		var file = $('#uploadefile').get(0).files;
		var data = new FormData;
		data.append("upload", file[0]);

		$.ajax({
			type: "POST",
			method: 'POST',
			url: 'WebService1.asmx/insertFileupload',
			//contentType: 'application/json;charset=utf-8',
			data: data,
			contentType: false,
			processData:false,
			success: function (data) {
				alert('s');
			},
			error: function (err) {
				alert(err);
			}
		});
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="btn_upload" type="button" value="example" /><br />
<input id="uploadefile" type="file" />

我的网络服务功能 enter image description here

[WebMethod]
public void insertFileupload(attachment data)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TesterConnectionString1"].ConnectionString);
    using (con)
    {
        SqlCommand cmd = new SqlCommand("attach_insert", con);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter()
        {
            ParameterName = "@image",
            Value = data.image
        });

        con.Open();
        cmd.ExecuteNonQuery();
    }   
}

最佳答案

将以下属性添加到您的网络服务类

[System.Web.Script.Services.ScriptService]

除上述之外,还可以将以下属性添加到您的 web 方法中

[ScriptMethod]

如果上述更改仍然无效,请确保您已在 web.config 中添加以下设置

<system.web>
<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

更新 无需在上传方法中传递任何参数。查看以下代码片段。

网络服务.asmx

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

namespace WebApplication10
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [ScriptMethod]
        [WebMethod]
        public void UploadFile()
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                // Get the uploaded image from the Files collection
                var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

                if (httpPostedFile != null)
                {
                    //var fileSavePath = Path.Combine(Server.MapPath("upload"), httpPostedFile.FileName);
                    //  var file = ConvertToByteArray(fileSavePath);
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TesterConnectionString1"].ConnectionString);
                    using (con)
                    {
                        SqlCommand cmd = new SqlCommand("attach_insert", con);
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.Add("@image", SqlDbType.VarBinary,
                            (int)httpPostedFile.InputStream.Length).Value = httpPostedFile.InputStream;
                            con.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
            public byte[] ConvertToByteArray(string varFilePath)
            {
                byte[] file;
                using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        file = reader.ReadBytes((int)stream.Length);
                    }
                }
                return file;
            }
        }
    }

WebForm1.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <input id="btn_upload" type="button" value="example" /><br />
            <input id="uploadefile" type="file" />
        </div>
    </form>
</body>
<script type="text/javascript">
$(document).ready(function () {

    $('#btn_upload').on('click', function () {

      var data = new FormData();
      var files = $("#uploadefile").get(0).files;
      // Add the uploaded image content to the form data collection
      if (files.length > 0) {
           data.append("UploadedImage", files[0]);
      }

      // Make Ajax request with the contentType = false, and procesDate = false
      var ajaxRequest = $.ajax({
           type: "POST",
           url: "/WebService1.asmx/UploadFile",
           contentType: false,
           processData: false,
           data: data
           });

      ajaxRequest.done(function (xhr, textStatus) {
                    // Do other operation
             });
   });
});
</script>
</html>

关于javascript - 使用 ajax 和 asp.net 将文件保存到 SQL Server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47978323/

相关文章:

javascript - 如何拥有不同颜色的提示工具提示?

jquery - 将标记(气泡)添加到简单的内容幻灯片中

javascript - 如何从现有的第 3 方控件链接 jQuery 事件?

c# - 在服务器端代码中使用 for 循环通过在标签中动态创建名称来循环标签

javascript - react native : functions are not valid as a react child . 如果您返回组件而不是 <component/>,则可能会发生这种情况

javascript - 尝试创建一个简单的 'mastermind-like' 游戏

javascript - 如何使用 d3.js 将纬度和经度转换为 (x,y) 坐标

jquery - jQuery 选择器可以与 DOM 突变观察器一起使用吗?

javascript - 砌体不再有动画

c# - 使用 LINQ to SQL 记录更改