您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Javascript:正在上传文件…没有文件

Javascript:正在上传文件…没有文件

为什么不只XMLHttpRequest()与POST一起使用?

function beginQuoteFileUnquoteUpload(data)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://www.mysite.com/myuploadhandler.PHP", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function ()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
            alert("File uploaded!");
    }
    xhr.send("filedata="+encodeURIComponent(data));
}

服务器上的处理程序脚本仅将文件数据写入文件

文件上传仍然是具有不同内容类型的http帖子。您可以使用此内容类型,并用边界分隔内容

function beginQuoteFileUnquoteUpload(data)
{
    // Define a boundary, I stole this from IE but you can use any string AFAIK
    var boundary = "---------------------------7da24f2e50046";
    var xhr = new XMLHttpRequest();
    var body = '--' + boundary + '\r\n'
             // Parameter name is "file" and local filename is "temp.txt"
             + 'Content-Disposition: form-data; name="file";'
             + 'filename="temp.txt"\r\n'
             // Add the file's mime-type
             + 'Content-type: plain/text\r\n\r\n'
             + data + '\r\n'
             + boundary + '--';

    xhr.open("POST", "http://www.mysite.com/myuploadhandler.PHP", true);
    xhr.setRequestHeader(
        "Content-type", "multipart/form-data; boundary="+boundary

    );
    xhr.onreadystatechange = function ()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
            alert("File uploaded!");
    }
    xhr.send(body);
}

如果要发送其他数据,只需在每个部分之间加一个边界,然后描述每个部分的content-disposition和content- type标头。每个标头由换行符分隔,正文与标头由附加的换行符分隔。自然,以这种方式上传二进制数据会稍微困难一些:-)

进一步编辑:忘记提及,请确保要发送的文本“文件”中没有任何边界字符串,否则它将被视为边界。

javascript 2022/1/1 18:17:16 有450人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶