2

I have used ajax and asp.net to insert file to my sqlserver2012 database and i got error result as shown below :
my error localhost:6446 syas : [object Object]

in HTML and 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" />

My WebService function 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();
    }   
}

1 Answer 1

1

Add following Attribute to your webservice class

[System.Web.Script.Services.ScriptService]

Apart from above also add following attribute to your webmethod

[ScriptMethod]

If above changes still not working make sure you have added following settings in web.config

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

Update No need to pass any parameter in upload method.Check out following code snippet.

WebService.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>
Sign up to request clarification or add additional context in comments.

12 Comments

i added this but i got the same error which is "localhost:6446 syas : [object Object] " becuase i think i don't know what is the type of the Parameter in the webServices
@HelloItsMe let me create a sample application for you
not work i got the error fileNotFoundException was unhandled by user code
make sure UploadedFiles folder exist in root
i checked file path and folder is exist but i got error in this code "var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.