如何从浏览器上传文件(附件)? [英] How to upload a file (attachment) from the browser?

查看:1177
本文介绍了如何从浏览器上传文件(附件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有上传附件才能使浏览器正常工作。



某些提示是此处,其他文档很好,但是我无法将其转换为AJAX上传。



我正在寻找一个超简单的HTML / JavaScript示例(带有jQuery或不带有jQuery),该示例如何将文件从(相对较新的)浏览器上传到数据库没有使用jquery.couch.app.js包装器或其他东西。

任何帮助表示赞赏。

解决方案

好的,这是您的纯JavaScript文件上传实现。



基本算法是这样的:


  1. 从文件输入元素中获取文件

  2. 获取文件名并键入文件对象

  3. 获取要将文件附加到的文档的最新文档版本

  4. 将文件附加到文档使用获取的修订版本

HTML部分基本上由带有两个元素的简单形式组成,输入类型为文件和类型为提交的按钮。

 < form action = / method = post name = upload> 
< input type = file name = file />
< button type = submit name = submit>上传< / button>
< / form>

现在是JavaScript部分。

  window.onload = function(){
var app = function(){
var baseUrl ='http://127.0.0.1 :5984 / playground /';
var fileInput = document.forms ['upload']。elements ['file'];
document.forms ['upload']。onsubmit = function(){
uploadFile('foo',fileInput.files [0]);
返回false;
};

var uploadFile = function(docName,file){
var name = encodeURIComponent(file.name),
type = file.type,
fileReader =新的FileReader (),
getRequest =新的XMLHttpRequest(),
putRequest =新的XMLHttpRequest();

getRequest.open('GET',baseUrl + encodeURIComponent(docName),
true);
getRequest.send();
getRequest.onreadystatechange =函数(响应){
if(getRequest.readyState == 4&& getRequest.status == 200){
var doc = JSON.parse(getRequest。 responseText);
putRequest.open('PUT',baseUrl +
encodeURIComponent(docName)+‘/’+
name +‘?rev =’+ doc._rev,true);
putRequest.setRequestHeader(‘Content-Type’,类型);
fileReader.readAsArrayBuffer(file);
fileReader.onload =函数(readerEvent){
putRequest.send(readerEvent.target.result);
};
putRequest.onreadystatechange = function(response){
if(putRequest.readyState == 4){
console.log(putRequest);
}
};
}
};
};
};
app();
};

基本上,我截获了 submit 事件通过将我自己的函数绑定到表单的 onsubmit 事件并返回false。



在该事件处理程序中,我的主要功能有两个参数。第一个是文档名称,第二个是要上传的文件。



在我的 uploadFile()中函数我设置文件名,文件类型并获取一些实例。第一个HTTP请求是一个GET请求,用于获取文档的当前版本。如果该请求成功,则通过设置先前获得的修订,正确的内容类型来准备PUT请求(实际的上传请求),然后将文件转换为ArrayBuffer。完成后,我将发送刚刚准备好的HTTP请求,然后放松。



独立附件上传方案如下:

  PUT主机/数据库/文档/文件名?revision =最新版本

当然,请在HTTP请求标头中使用正确的内容类型。



注意:我很清楚我根本没有在这里使用防御性程序设计,为了简洁起见,我故意这样做。


I don't get attachment upload for the browser to work.

Some hints are here, others there. The docs are quite good but I'm unable to translate that to a AJAX upload.

I'm looking for a super simple HTML/JavaScript example (with or w/o jQuery) of how to upload a file from (relatively modern) browser to the db without making use of jquery.couch.app.js wrapper or stuff. The simpler the besser.

Any help appreciated.

解决方案

Alright, here's your pure JavaScript file upload implementation.

The basic algorithm is like this:

  1. Get the file from the file input element
  2. Get the file name and type off the file object
  3. Get the latest document revision of the document you want to attach the file to
  4. Attach the file to document using the fetched revision

The HTML part basically consists of a simple form with two elements, an input of type file and a button of type submit.

<form action="/" method="post" name="upload">
  <input type="file" name="file" />
  <button type="submit" name="submit">Upload</button>
</form>

Now to the JavaScript part.

window.onload = function() {
    var app = function() {
        var baseUrl = 'http://127.0.0.1:5984/playground/';
        var fileInput = document.forms['upload'].elements['file'];
        document.forms['upload'].onsubmit = function() {
            uploadFile('foo', fileInput.files[0]);
            return false;
        };

        var uploadFile = function(docName, file) {
            var name = encodeURIComponent(file.name),
            type = file.type,
            fileReader = new FileReader(),
            getRequest = new XMLHttpRequest(),
            putRequest = new XMLHttpRequest();

            getRequest.open('GET',  baseUrl + encodeURIComponent(docName),
                true);
            getRequest.send();
            getRequest.onreadystatechange = function(response) {
                if (getRequest.readyState == 4 && getRequest.status == 200) {
                    var doc = JSON.parse(getRequest.responseText);
                    putRequest.open('PUT', baseUrl +
                        encodeURIComponent(docName) + '/' +
                        name + '?rev=' + doc._rev, true);
                    putRequest.setRequestHeader('Content-Type', type);
                    fileReader.readAsArrayBuffer(file);
                    fileReader.onload = function (readerEvent) {
                        putRequest.send(readerEvent.target.result);
                    };
                    putRequest.onreadystatechange = function(response) {
                        if (putRequest.readyState == 4) {
                            console.log(putRequest);
                        }
                    };
                }
            };
        };
    };
    app();
};

Basically, I intercept the submit event of the form by binding my own function to the form's onsubmit event and returning false.

In that event handler I call my main function with two parameters. The first one being the document name and the second one being the file to upload.

In my uploadFile() function I set the file name, file type and grab some instances. The first HTTP request is a GET request to obtain the current revision of the document. If that request succeeds I prepare the PUT request (the actual upload request) by setting the previously obtained revision, the proper content type and then I convert the file to an ArrayBuffer. Once that's done I just send the HTTP request I've just prepared and then I relax.

The standalone attachment upload scheme looks like this:

PUT host/database/document/filename?revision=latest-revision

Of course using the proper content type in the HTTP request header.

Note: I'm well aware that I'm not making use of defensive programming here at all, I did that deliberately for brevity.

这篇关于如何从浏览器上传文件(附件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆