-4

can i send file through java script to web Service in asp.net? If yes, how to send that file? Need to Convert the file into byte array...? this my code send file through javascript?please see my code below

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            Id:  
            <asp:TextBox ID="txtId" runat="server"></asp:TextBox><br />

            File:
            <asp:FileUpload ID="FileUpload1" runat="server" /><br />
                   <asp:HiddenField ID="HiddenField1" runat="Server"/>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Button1_Click" />



        </div>
    </form>
</body>

this is my script.i got bytes in alert but webservice is not calling....in browser only got exception

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    var id = document.getElementById("txtId").value;
    var byteArrays = [];
    function getFile() {
        debugger;


        var data = document.getElementById("FileUpload1");
        // var file = $("#objFile")[0].files[0];
        var file = data.files[0];
        fr = new FileReader();
        fr.onload = receivedText;
        //fr.readAsText(file);
        fr.readAsDataURL(file);
    }

    function receivedText() {
        var b64Data = fr.result.split(',');
        var contentType = 'image/jpeg';
        //document.getElementById('editor').appendChild(document.createTextNode(fr.result))
        var byteCharacters = atob(b64Data[1]);
        var byteNumbers = Array.prototype.map.call(byteCharacters,
                                       charCodeFromCharacter);
        var uint8Data = new Uint8Array(byteNumbers);
        var blob = b64toBlob(b64Data[1], contentType);
        //var blobUrl = URL.createObjectURL(blob);
    }

    function charCodeFromCharacter(c) {
        return c.charCodeAt(0);
    }

    function b64toBlob(b64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 1024;
        var byteCharacters = atob(b64Data);


        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
            var byteNumbers = Array.prototype.map.call(slice, charCodeFromCharacter);
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
            for (var i = 0; i < byteArray.length; i++) {
                alert(byteArray[i]);
            }

        }

        $.ajax({
            url: "http://localhost:51963/FileUploadService.asmx/ServiceForFileUpLoad",
            data: { ID: id, Data: file },
            contentType: "application/json; charset=utf-8",
            type: "GET",
            success: function (data) {
                alert(data);
            },
            error: function (x, y, z) {
                alert(x.responseText + "  " + x.status);
            }
        });
    }


</script>
</html>

this is my service code

[webmethod]
     public string UploadDataService(int id, byte[] bytes)
            {
                return "sucess";
            }
5
  • There are numerous examples on StackOverflow. Have you tried a Google search or even searching StackOverflow? Commented Nov 1, 2016 at 6:49
  • 1
    Possible duplicate of how to send uploaded file from javascript to controller in MVC? Commented Nov 1, 2016 at 6:55
  • Thanks for your reply.I have tried.I converted file into bytes .while sending bytes to webservice getting timedout exception. Commented Nov 1, 2016 at 8:41
  • Can we see your 'FileUploadService.asmx/ServiceForFileUpLoad' file? does it even exist? Commented Nov 1, 2016 at 9:39
  • yaa sure.just i returned simple sucess for checking webservice is calling or not. Commented Nov 1, 2016 at 9:51

1 Answer 1

0

I have no idea why you read a file as dataURL and then recreate the file but as a blob... pointless

  • Use multipart form upload when uploading files included with custom fields
  • Don't read it as dataURL and send everything as a json object. the file will be ~3x larger for upload and it also takes time to compile/decompile
  • Sending a form data with jQuery is never easy (see how), that is why i prefer the new fetch api, that + it's promisifyed so you can use async/await

window.upload = async function(evt) {
  evt.preventDefault()
  
  let form1 = document.getElementById('form1')
  let body = new FormData(form1)
  let opts = {
    method: 'post',
    body
  }
  
  let res = await fetch('https://httpbin.org/post', opts)
  let json = await res.json()
  console.log(json)
}
<form id="form1">
  <input name="id" value="2">
  <input name="txt" type="file">
  <input type="submit" onclick="upload(event)">
</form>

Sign up to request clarification or add additional context in comments.

Comments

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.