CouchDB に Web から、複数の画像をアップロード

CouchDB に、Web インターフェースを通して、複数の画像をアップロードする方法です。URL を変えれば、Bluemix の Cloudant にも使えます。
サーバーサイドで、python3 の requests を使っています。

![couchdb_jul30.png](https://qiita-image-store.s3.amazonaws.com/0/179446/ee3d978b-3412-cc75-2632-2f5f160ee626.png)


```html:couchdb_upload.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<script src="/js/jquery-3.2.1.min.js"></script>
<script src="couchdb_upload.js"></script>
<title>CouchDB　アップロード (Jul/30/2017)</title>
</head>
<body>
<h2>CouchDB　アップロード (Jul/30/2017)</h2><p />
<div class="top">
</div>

<hr />
送るファイルを選んで下さい。<p />
<form action="javascript:;">
<input type="file" id="file" multiple="multiple" />
<input type="submit" id="upload" value="送信" />
</form>
<hr />
<div id="message">message</div>
<hr />
アップロードするデータサイズの指定<p />
/etc/nginx/nginx.conf<p />
<blockquote>
<pre>
    server {
        client_max_body_size 20M;
        listen       80;
        server_name  localhost;
</pre>
</blockquote>
<hr />
<div id="outarea_aa">outarea_aa</div>
<div id="outarea_bb">outarea_bb</div>
<div id="outarea_cc">outarea_cc</div>
<div id="outarea_dd">outarea_dd</div>
<div id="outarea_ee">outarea_ee</div>
<div id="outarea_ff">outarea_ff</div>
<div id="outarea_gg">outarea_gg</div>
<div id="outarea_hh">outarea_hh</div>
<hr />
Jul/30/2017 AM 08:15<p />
</body>
</html>
```

```js:couchdb_upload.js
// -----------------------------------------------------------------------
//	couchdb_upload.js
//
//					Jul/30/2017
//
// -----------------------------------------------------------------------
jQuery (function ()
{
	jQuery("#outarea_aa").html
		("*** couchdb_upload *** start *** Jul/30/2017 ***")

	const collection = "jpg"

	upload_click_monitor (collection)

	jQuery("#outarea_hh").html
		("*** couchdb_upload *** end *** Jul/30/2017 ***")

})

// -----------------------------------------------------------------------
// [4]:
function upload_click_monitor (collection)
{
	jQuery("#upload").bind ("click",function()
		{
		jQuery ("#outarea_bb").html ("*** upload clicked ***<br />")

		if (jQuery("#file").val() !== '')
			{
			var fd = new FormData()

			var files=jQuery("#file").prop("files")

			for (var it=0; it< files.length; it += 1)
				{
				const fname="file_" + it
				fd.append (fname,files[it])
				}

			fd.append("collection",collection)
 
			python_upload_proc (fd)
			}
		})
}

// -----------------------------------------------------------------------
// [4-4]:
function python_upload_proc (fd)
{
// dataにFormDataを指定する場合 processData,contentTypeをfalseにして
// jQueryがdataを処理しないようにする

	var postData = {
		type : "POST",
		dataType : "json",
		data : fd,
		processData : false,
		contentType : false
		}

	const url_action = "./couchdb_upload.py"

	jQuery.ajax (url_action,postData).done(function (rec)
		{
		jQuery ("#outarea_dd").html ("*** done ***<br />")

		var str_message = "<blockquote>"
		for (var it in rec['message'])
			{
			str_message += rec['message'][it] + '<br />'
			}

		str_message += "</blockquote>"

		jQuery ("#message").html (str_message)
		})
}

// -----------------------------------------------------------------------
```

```py3:couchdb_upload.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	couchdb_upload.py
#
#					Jul/30/2017
#
# --------------------------------------------------------------------
import	sys
import	json
import	cgi
import	os
import	struct
import	requests
# --------------------------------------------------------------------
# [4]:
def data_upload_proc(collection,key,data):
	message = []
	url="http://localhost:5984"
	jpg_in = key + ".jpg"
	url_jpg_file = url + "/" + collection + "/" + key + "/" + jpg_in
#
	headers = {'Content-type': 'image/jpeg'}
#
	try:
		rr=requests.put(url_jpg_file, data=data,headers=headers)
	except Exception as ee:
		message.append ("*** error *** from requests.put ***")
		message.append (str (ee))
#
	return	message
# --------------------------------------------------------------------
def single_upload_data_proc (collection,item):
	message = []
	file_in = item.filename
	fname = os.path.basename (file_in)
	arrays=fname.split(".")
	key = arrays[0]
	message.append ("key = " + key)
	chunk = item.file.read ()
	if chunk:
		try:
			message += data_upload_proc(collection,key,chunk)
		except Exception as ee:
			message.append (str (ee))
#
	return message
# --------------------------------------------------------------------
message = []
message.append ("*** start *** couchdb_upload.py ***")
form = cgi.FieldStorage()
#
collection = form["collection"].value
message.append ("collection = " + collection)
#
count = 0
for key in form:
	if (key != "collection"):
		item = form[key]
		message += single_upload_data_proc (collection,item)
#
		count += 1
#
message.append ("count = %d" % count) 
message.append ("*** end *** couchdb_upload.py ***")
rvalue = {}
rvalue["message"] = message
out_str = json.dumps (rvalue)
#
print ("Content-Type: application/json")
print ("")
#
print (out_str)
# --------------------------------------------------------------------
```