使用表单输入访问相机,并立即上传照片使用web应用

时间:2022-11-30 11:37:40

I came across this answer which is brilliant:

我遇到了这个非常棒的答案

In iPhone iOS6 and from Android ICS onwards, HTML5 has the following tag which allows you to take pictures from your device:

在iPhone iOS6和Android ICS上,HTML5有以下标签,可以让你从你的设备上拍照:

    <input type="file" accept="image/*" capture="camera">

Capture can take values like camera, camcorder and audio.

捕获可以获取相机、摄像机和音频等值。

Is it possible to take this one step further by using ajax of some kind to immediately upload photo after its taken?

是否有可能更进一步,使用某种类型的ajax,在拍摄后立即上传照片?

For example, using my phone, once I tap on the input, it then opens the camera which will immediately allow me to take a photo and save it. When I save it to camera, it's then listed by the input button as the file to upload.

例如,使用我的手机,一旦我点击输入,它就会打开摄像头,让我立即拍照并保存。当我将它保存到相机时,输入按钮将它作为要上传的文件列出。

What would it take for this photo to be immediately uploaded instead of waiting for the user to click the Submit button of the form?

要立即上传这张照片而不是等待用户点击表单的Submit按钮,需要什么?

1 个解决方案

#1


76  

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

这样做非常简单,只需在文件输入的onchange处理程序中通过XHR请求发送文件。

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

#1


76  

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

这样做非常简单,只需在文件输入的onchange处理程序中通过XHR请求发送文件。

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);