Uploading file with AngularJS fails - python

Below are the snippets of my code regarding file upload.
Here is my HTML code where I will choose and upload the file:
<form ng-click="addImportFile()" enctype="multipart/form-data">
<label for="importfile">Import Time Events File:</label><br><br>
<label for="select_import_file">SELECT FILE:</label><br>
<input id="import_file" type="file" class="file btn btn-default" ng-disabled="CutOffListTemp.id== Null" data-show-preview="false">
<input class="btn btn-primary" type="submit" name="submit" value="Upload" ng-disabled="CutOffListTemp.id== Null"/><br/><br/>
</form>
This is my controller that will link both html and my python file:
angular.module('hrisWebappApp').controller('ImportPayrollCtrl', function ($scope, $state, $stateParams, $http, ngTableParams, $modal, $filter) {
$scope.addImportFile = function() {
$http.post('http://127.0.0.1:5000/api/v1.0/upload_file/' + $scope.CutOffListTemp.id, {})
.success(function(data, status, headers, config) {
console.log(data);
if (data.success) {
console.log('import success!');
} else {
console.log('importing of file failed' );
}
})
.error(function(data, status, headers, config) {});
};
This is my python file:
#api.route('/upload_file/<int:id>', methods=['GET','POST'])
#cross_origin(headers=['Content-Type'])
def upload_file(id):
print "hello"
try:
os.stat('UPLOAD_FOLDER')
except:
os.mkdir('UPLOAD_FOLDER')
file = request.files['file']
print 'filename: ' + file.filename
if file and allowed_file(file.filename):
print 'allowing file'
filename = secure_filename(file.filename)
path=(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
file.save(path) #The end of the line which save the file you uploaded.
return redirect(url_for('uploaded_file',
filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<p>opsss it seems you uploaded an invalid filename please use .csv only</p>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
And the result in the console gave me this even if I select the correct format of file:
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<p>opsss it seems you uploaded an invalid filename please use .csv only</p>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
This is not returning to my HTML and I cannot upload the file.

Hi I can finally upload the file, I change the angular part, I change it by this:
$scope.addImportFile = function() {
var f = document.getElementById('file').files[0]; console.log(f);
var formData = new FormData();
formData.append('file', f);
$http({method: 'POST', url: 'http://127.0.0.1:5000/api/v1.0/upload_file/' +$scope.CutOffListTemp.id,
data: formData,
headers: {'Content-Type': undefined},
transformRequest: angular.identity})
.success(function(data, status, headers, config) {console.log(data);
if (data.success) {
console.log('import success!');
}
})
.error(function(data, status, headers, config) {
});
// }
};

The first thing is about the post request. Without ng-click="addImportFile()", the browser will usually take care of serializing form data and sending it to the server. So if you try:
<form method="put" enctype="multipart/form-data" action="http://127.0.0.1:5000/api/v1.0/upload_file">
<label for="importfile">Import Time Events File:</label><br><br>
<label for="select_import_file">SELECT FILE:</label><br>
<input id="import_file" type="file" name="file" class="file btn btn-default" ng-disabled="CutOffListTemp.id== Null" data-show-preview="false">
<input class="btn btn-primary" type="submit" name="submit" value="Upload" ng-disabled="CutOffListTemp.id== Null"/><br/><br/>
</form>
and then in python, make your request url independent of scope.CutOffListTemp.id:
#api.route('/upload_file', methods=['GET','POST'])
It probably will work.
Alternatively, if you want to use your custom function to send post request, the browser will not take care of the serialization stuff any more, you will need to do it yourself.
In angular, the API for $http.post is:
$http.post('/someUrl', data).success(successCallback);
If we use "{}" for the data parameter, which means empty, the server will not find the data named "file" (file = request.files['file']). Thus you will see Bad Request
To fix it, we need to use formData to make file upload which requires your browser supports HTML5:
$scope.addImportFile = function() {
var f = document.getElementById('file').files[0]
var fd = new FormData();
fd.append("file", f);
$http.post('http://127.0.0.1:5000/api/v1.0/upload_file/'+$scope.CutOffListTemp.id,
fd,
headers: {'Content-Type': undefined})
.success......
Other than using the native javascript code above, there are plenty great angular file upload libraries which can make file upload much easier for angular, you may probably want to have a look at one of them (reference: File Upload using AngularJS):
https://github.com/nervgh/angular-file-upload
https://github.com/leon/angular-upload
......

Related

How to download file using url which getting authenticated via sso

I have URL= "https://Path-to-url&Action=Download&format=CSV" which i am hitting into browser it is able to download csv file with correct data because it is getting authenticated with SSO. But when i am using python it is downloading file but getting authentication error. I gave mt creds as well for authentication but it didn't worked. Here is my code.
url = "https://Path-to-url&Action=Download&format=CSV"
user,password = 'user-name', 'password'
response = requests.get(url,auth=(user, password))
open("BGCustomersbySKU-OCI.csv", "wb").write(response.content)
Error which i am getting
<script language="javascript" type="text/javascript">
function submitForm()
{
var hash = location.hash;
if (hash) {
if(hash.indexOf("#") == -1){
hash="#"+hash
}
document.myForm.action = document.myForm.action+hash;
}
document.myForm.submit();
}
</script><head><base target="_self"></head><body onLoad="submitForm()"><noscript><p>JavaScript is required. Enable JavaScript to use OAM Server.</p></noscript><form action="https://login.com/mysso/signon.jsp" method="post" name="myForm"><!------------ DO NOT REMOVE -------------><!----- loginform renderBrowserView -----><!-- Required for SmartView Integration --><input type="hidden" name="bmctx" value="A38E9D6A49EE1821DBE253981B42CC214C0510AD855BCE41264037D8AC1D3C3C"><input type="hidden" name="contextType" value="external"><input type="hidden" name="username" value="string"><input type="hidden" name="contextValue" value="%2Foam"><input type="hidden" name="challenge_url" value="https%3A%2F%2Flogin..com%2Fmysso%2Fsignon.jsp"><input type="hidden" name="password" value="sercure_string"><input type="hidden" name="request_id" value="5378585642023862909"><input type="hidden" name="authn_try_count" value="0"><input type="hidden" name="OAM_REQ" value="VERSION_4~xTenNhZzYIV523%2b3AJNb%2fG2zmo5aYdsS49LwauGiNsBQAI39zBBwx3cEBrX%2f%2ftlBIZEZK7vI1L%2f%2fHbdrGxAXw8MLpEF3NCnVEB0vFA7RkNhXJ%2ffNqmpOVz6Rem9QskdR%2fIdEDQ%2bIi5iZPYoUb04lGIlKps2VJs6pVw4nS%2bDofQx%2bLUIg4sgYmNIXkNdnSa7e3U9pPmhpEjDjeofFQg25SELJsiQfHfqEEmIGlWkRP4xWch0xQ8mmQiTRHrvPH1wvUFBUhe9KGVKFMzDdaQX3bN3ThqpyBg7OarNBrlFjH61VF%2biWcqXDrzgezgMUBTBJf4JUdcQZa%2bvHM1k88EpcR5mr0SLtZIoKl%2b700LqFuRc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Jm%2bVF19BQc%2bS76%2fKpoTNvJcmHpqu4w8Z3OBdsS6ag%2fK6JEQniaVCr6BY0qL6NRtgBzVu6NLThUlVTxSMtkb35a9qQkgFeOfV1UhxS0rN5ybeZNzfFi4wIbctda0%2bI0lB4CLniJoprc32cY5y2C5lxUW1EHCVMeTA565nbg%2bq%2f91wA1NVvz1lNlsbzPfiGOGwovkmZTR5p%2fTe0OGH9tTBFpStgOPDJCU2o0v1WkisHPBU54COdG0fJUZp%2bm1IDQ2K%2fkGXJZLv4tJLeTgUeRJLxMw53K2M0rGZATmYEQ4HXaPPjMaahMOieph1DHDL9B26uZZHKNCS5ZpuFRX9E33rtDVFOvHXDNg%2bxjEl%2b410ujwwCRnu1ej3wasPI1geUlsDA2rfxKrsTM%2b8oMDMbWT6oTBy2WMV%2ff3dF6cmFUQmSQwF8rPAK7nmyA7%2f%2bdCxYz7ddgNirC%2```

How to get full path of selected file on change of <input type=‘file’> using django

compress.html
<form action="/compress" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label for="pdf">Select pdf :</label>
<input type="file" name="pdf1" id ="pdf1" accept="pdf/*" />
<br>
<button type="submit" class="btn btn-dark mt-2" value="click">
submit
</button>
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#fileUpload').val();
});
}
</script>
views.py
def mergepdf(request):
from pylovepdf.ilovepdf import ILovePdf
ilovepdf = ILovePdf('my_secrete_key', verify_ssl=True)
task = ilovepdf.new_task('compress')
task.request.FILES['full_path']# here i want full path of selected file
task.set_output_folder('/Downloads/download_pdffile')
task.execute()
task.download()
task.delete_current_task()
The filePath var contains the only name of selected file, not the full path.
I searched it on the net, but it seems that for security reasons browsers (FF, chrome) just give the name of the file.
Is there any other way to get the full path of the selected file?

Why is my POST not working after getting values

So I am getting user input from a template that uses css and jQuery, then I'm posting that data back supposedly on click. However, I am not able to access the data as I believe it is not being posted back.
I believe my ajax code is not recognizing the click, can someone please help me out. I spent the whole day trying to figure out what am I doing wrong.
#This is main code
from bottle import run, route, request, template, static_file, post
def main():
#This is main code
#route('/assets/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='./Gui/assets')
#route('/')
def home():
return template('indexTest')
#post('/home')
def home():
radius=request.forms['radius']
noTr=request.forms['noOdTurbines']
result=radius+noTr
return ({'result': result})
if __name__ == '__main__':
main()
run(host='localhost', port=8080, debug=True)
this is jQuery code
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script type="text/javascript">
$(document).ready(function(){
$('form').on('submit',(function(event){
$.ajax({
type: "POST",
url: "/home"
data: {
radius: $('#radius').val(),
noOfTurbines: $('#noOfTurbines').val()
},
error:function(){
alert('Error: something is wrong with values!!')
}
})
event.preventDefault();
});
}));
</script>
</head>
<body>
<form method="POST" action="/home">
<div id="exampleAccount" role="tabpanel">
<div id="exampleAccountForm">
</div>
<div>
<label for="radius">Radius of Swept-Area of Wind turbine:
</label>
<input type="text" id="radius" required>
</div>
<div >
<label for="noOfTurbines">Number of Wind turbines: </label>
<input type="text" id="noOfTurbines" required>
</div>
</div>
</div>
<div >
<button type="submit" class="btn btn-default"
id="submit">Finish</button>
</div>
</form>
</body>
</html>
I have problems with the request.forms type of multidict, so I convert to dict and this solves all my problems. I usually merge the post and string URL objects into one just to make it more flexible.
def merge_dicts(*args):
result = {}
for dictionary in args:
result.update(dictionary)
return result
payload = merge_dicts(dict(request.forms), dict(request.query.decode()))
Just remember, that bottle uses the name not the id of the form element in a post. So make sure all inputs have a name.
(Which I do not see in your example)

Passing File Objects with Django

I am attempting to retrieve a file and then upload it to Parse.com by submitting via POST. My HTML:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="container">
<form action="" id="fileupload" name="fileupload" enctype="multipart/form-data" method="post">
{% csrf_token %}
<fieldset>
<input type="file" name="fileselect" id="fileselect" /></input>
<input type="hidden" name="myFile" id="myFile" />
<input id="uploadbutton" type="submit" value="Upload to Parse" />
</fieldset>
</form>
</div>
And using the following function to retrieve the file:
<script type="text/javascript">
$(function() {
var file;
// Set an event listener on the Choose File field.
$('#fileselect').bind("change", function(e) {
var files = e.target.files || e.dataTransfer.files;
// Our file var now holds the selected file
file = files[0];
document.getElementById('myFile').value = file;
});
});
</script>
However, this "myFile" field is not posting the file as an object nor does it jive with the Parse API documentation, which appears to be looking for a file path name, which I don't think I can pull from an unknown machine.
import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/files/pic.jpg', open('myPicture.jpg','rb').read(), {
"X-Parse-Application-Id": "xxxxxxxxxxxxxxxxxxxxx",
"X-Parse-REST-API-Key": "xxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type": "image/jpeg"
})
result = json.loads(connection.getresponse().read())
print result
This seems like it would be a common use case but the only documentation I found was for ajax, which I would prefer not to use because it exposes my API credentials https://www.parse.com/questions/uploading-files-to-parse-using-javascript-and-the-rest-api.
I am not sure what is the best way to handle the file... if there's a way to handle within the Django framework or if I need to convert to JSON. And, even when the file object is captured, I'm not clear on how to use the Parse.com API with the file object.
After some research, it turns out that the answer is pretty straightforward. Using the "Basic File Upload" documentation from the Django website: https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/ and replacing
open('myPicture.jpg', 'rb').read()
in the Parse documentation (referenced in the question above) with
request.FILES['file']
I was able to successfully upload the file to Parse. No javascript necessary.

Python - simple requests file upload didn't work

i created a simple html upload file :
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
and a simple php upload file :
<?php
$target_dir = "";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>
i tested everything works perfectly
i want to submit a file upload with python using requests module so i created this :
import requests
url = 'http://localhost/upload/up.html'
files = [('images', ('1.jpg', open('1.jpg', 'rb'), 'image/jpg'))]
r = requests.post(url, files=files)
print r.text
it will return the html page code and the file uploading is failed , any solution ?
I think the issue is the name passed to post. Use fileToUpload rather than images like this:
files = [('fileToUpload', ('1.jpg', open('1.jpg', 'rb'), 'image/jpg'))]
r = requests.post(url, files=files)

Categories

Resources