Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

html上传文件-python后台接收文件 #4

Open
leon0625 opened this issue Jan 13, 2018 · 0 comments
Open

html上传文件-python后台接收文件 #4

leon0625 opened this issue Jan 13, 2018 · 0 comments
Labels

Comments

@leon0625
Copy link
Owner

leon0625 commented Jan 13, 2018

html传输文件-python后台接收文件

html端
这里只使用file type的input,不使用form来上传

<input type="file" id="upload_file_name" name="upload" /> 
<input type="button" value="上传图片" onclick="upload_image()"/> <span id="upload_status"></span><br/>

js端
formData.append可以添加你需要的其他数据上去,这里我添加了一个"action": "upload_image"上去

function flush_result(obj) {
	if(obj["action"] == "upload_image"){
		if(obj["error"] != "ok"){
			$("#upload_status").text("上传失败");
		}
		else{
			$("#upload_status").text('上传成功');
		}
		return;
	}
}

function upload_image(){
	var formData = new FormData();
	formData.append('action', 'upload_image')
	formData.append('file', $('#upload_file_name')[0].files[0]);
	$.ajax({
	    url: '/cgi-bin/feeling.py',
	    type: 'POST',
	    cache: false,
	    data: formData,
	    processData: false,
	    contentType: false
	}).done(function(res){
		flush_result(res);
	}).fail(function(res){
		flush_result(res);
	});
}

python端
保存文件到/tmp目录下

#!/usr/bin/python3

import os,sys,requests,cgi,json
import codecs

def upload_image_action(form):	
	response = {}
	response["action"] = form.getvalue('action')
	fileitem = form['file']
	try:
		fn = os.path.basename(fileitem.filename)
		open('/tmp/' + fn, 'wb').write(fileitem.file.read())
		response["error"] = "ok"
	except:
		response["error"] = "error"

	print("Content-type: application/json\r\n\r\n")
	print(json.dumps(response))

form = cgi.FieldStorage() 
action = form.getvalue('action')

if action == 'upload_image':
	upload_image_action(form)

ok!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant