HTTP请求边界JavaScript

时间:2011-10-12 16:09:54

标签: c# javascript ajax header xmlhttprequest

我想知道如何处理边界中的二进制数据......现在我的代码是提交原始数据,但我不知道如何将它包装起来以供我的C#看到。

这是我目前的代码......

/*global window, document, XMLHttpRequest, FormData, FileReader, Uint8Array, alert, BlobBuilder, navigator */


function sendForm(filefield) {
"use strict";
var reader, filedata, bb, xhr, blobber;
filedata = document.getElementById(filefield).files[0];
reader = new FileReader();
reader.onloadend = function (evt) {
    if (evt.readyState === FileReader.Done) {
        if (navigator.userAgent.indexOf("Chrom") !== -1) {
            bb = new window.WebKitBlobBuilder();
        } else if (navigator.userAgent.indexOf("Firefox") !== -1) {
            bb = new window.MozBlobBuilder();
        } else {
            bb = new BlobBuilder();
        }
        bb.append(reader.result);
        blobber = bb.getBlob();
        xhr = new XMLHttpRequest();
        xhr.open("POST", "imageprocessor.aspx", true);
        xhr.setRequestHeader("Content-type", "image/png");
        xhr.setRequestHeader("Content-length", reader.length);
        xhr.send(blobber);
    }
};
reader.readAsArrayBuffer(filedata);
}


window.onload = function () {
"use strict";
document.getElementById("sender").onclick = function () {
    sendForm("file");
};
};

我的HTML ...

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
    <title>Test</title>
    <script src="fileuploader.js" type="text/javascript"></script>
</head>

<body>
    <div>
        <input type="file" name="file" id="file" />
    </div>
    <div><input type="button" value="送る" id="sender" /></div>
</body>
</html>

我的C#......

<%@ Page language="C#" validateRequest=false %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Threading" %>
<script language="C#" runat="server">

private void Page_Load (object sender, System.EventArgs e)
{
int loop1;
HttpFileCollection Files;

Files = Request.Files; // Load File collection into HttpFileCollection variable.
Response.Write(Files.Count);
//  arr1 = Files.AllKeys;  // This will get names of all files into a string array.
//  for (loop1 = 0; loop1 < arr1.Length; loop1++)
//  {
//      Response.Write("File: " + Server.HtmlEncode(arr1[loop1]) + "<br />");
//      Response.Write("  size = " + Files[loop1].ContentLength + "<br />");
//      Response.Write("  content type = " + Files[loop1].ContentType + "<br />");
//  }

}

</script>

基本工作流程是:

“用户提交图像,在上传图像时发生事情(更新进度条或其他内容),图像发布到处理页面,页面将图像保存到自己的文件,源页面显示已完成”

1 个答案:

答案 0 :(得分:0)

您没有发送MIME编码文件,只是发送文件内容,因此HttpRequest.Files对您没用。使用HttpRequest.InputStream阅读您发布的内容。