如何通过javascript将文件发送到webservice?

时间:2016-11-01 06:46:17

标签: javascript jquery asp.net

我可以通过java脚本将文件发送到asp.net中的web服务吗?如果是,如何发送该文件?需要将文件转换为字节数组......? 这个我的代码通过javascript发送文件?请参阅下面的代码

<%@ 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>

这是我的script.i得到了提醒的字节但是webservice没有调用....在浏览器中只有异常

<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>

这是我的服务代码

[webmethod]
     public string UploadDataService(int id, byte[] bytes)
            {
                return "sucess";
            }

1 个答案:

答案 0 :(得分:-1)

我不知道为什么你把文件作为dataURL读取然后重新创建文件但是作为一个blob ...毫无意义

  • 上传自定义字段附带的文件时使用多部分表单上传
  • 不要将其作为dataURL读取并将所有内容作为json对象发送。上传文件大约3倍,编译/反编译也需要时间
  • 使用jQuery发送表单数据绝非易事(see how),这就是为什么我更喜欢新的fetch api,而且它已被宣传,因此你可以使用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>