5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python3: ファイルのアップロード (cgi)

Last updated at Posted at 2021-04-10

jQuery を使わないで Python3 の cgi でファイルをアップロードする方法です。
複数のファイルを同時にアップロードできます。
upload_python.png

upload_python.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>upload python (Apr/11/2021)</title>
</head>
<body>
<h2>HTML5</h2>
<form method="post" action="upload_python.py" enctype="multipart/form-data">
<input type="file" name="files"  multiple>
<p><input type="submit" value="送信する"></p>
</form>

<blockquote>
<p>File is uploaded to /tmp.</p>
</blockquote>
<hr />
Nginx<br />
<blockquote>
	<pre>
	server {
		client_max_body_size 20M;
	</pre>
</blockquote>
<hr />
Apr/11/2021 AM 08:25<p />
</body>
</html>
upload_python.py
# ! /usr/bin/python3
# -*- coding: utf-8 -*-
#
#	upload_python/upload_python.py
#
#					Apr/11/2021
#
# --------------------------------------------------------------------
import os
import sys
import cgi
#
# --------------------------------------------------------------------
def single_upload_file_proc(upload_dir,item):
	filename = item.filename
	try:
		path = os.path.join(upload_dir,os.path.basename(filename))
		chunk = item.file.read()
		if chunk:
			fout = open(path,mode='wb')
			fout.write(chunk)
			print(filename + "<br />")
			fout.close()
			os.chmod(path, 0o666)
	except Exception as ee:
		print("*** error *** single_upload_file_proc ***<br />")
		print(filename + "<br />")
		print(str (ee))
		print("<br />")
# --------------------------------------------------------------------
def multi_uploaded_file_proc(upload_dir,fileitem):
#
	for item in fileitem:
		single_upload_file_proc(upload_dir,item)
#
# --------------------------------------------------------------------
upload_dir = "/tmp"
#
print("Content-Type: text/html")
print("")

form = cgi.FieldStorage()
if "files" in form:
	fileitem = form["files"]
	print(isinstance (fileitem,list))
	print("<br />")
	if (isinstance(fileitem,list)):
		multi_uploaded_file_proc(upload_dir,fileitem)
	else:
		single_upload_file_proc(upload_dir,fileitem)
else:
	print("*** Select files ***<br />")

print("*** end ***<br />")
#
# --------------------------------------------------------------------

jQuery を使ったアップロードのサンプル
Python3: ファイルのアップロード

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?