I am using simple file upload code. Its showing error :
Here is my code :
<input type="file" name="student_image" onchange="angular.element(this).scope().uploadFile(this.files)" ng-model="formData.studentImage" id="student_image">
$scope.uploadFile = function (files) {
var form_data = new FormData();
form_data.append("file", files[0]);
$http.post('process.php', form_data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
if (data == "failed") {
// if not successful, bind errors to error variables
$scope.errorFinal = "Failed";
} else {
$scope.formData.image_name = data;
}
}).error('failed');
};
Try This
angular.element(this).scope().uploadFile(this);
.
<input type="file" name="student_image" onchange="angular.element(this).scope().uploadFile(this)" ng-model="formData.studentImage" id="student_image">
JS
$scope.uploadFile = function(data){
console.log(data.files[0]);
};
Related
I am a beginner working with React.js and Quill.
I am trying to upload a file from my local machine by rewriting existing imageHandler. It does take the file, but do not upload it. The error is following: TypeError: Cannot read property 'quill' of undefined. Here is my code so far:
function imageHandler() {
console.log('Image Handler called');
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = async function () {
const file = input.files[0];
console.log('User trying to upload this:', file);
const formData = new FormData()
if (file !== null) {
formData.append('file', file)
}
fetch('https://smartquestionapi.advancity.net/Image', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(function (response) {
if (response.ok) {
return response.json()
} else {
return { "error": true }
}
}).then(function (json) {
console.log(file.name);
var cursorPosition = this.quill.getSelection();
var imagePath = "https://smartquestionapi.advancity.net/Images/" + file.name;
this.quill.insertEmbed(cursorPosition.index, 'image', imagePath, Quill.sources.USER);
return json;
}).catch(err => {
console.log("eror: ", err);
})
}.bind(this);
}
The code crushes exactly in then(function (json){ function.
I think is because you are not binding this in this part:
.then(function (json) {
console.log(file.name);
var cursorPosition = this.quill.getSelection();
You can solve it with an arrow function:
.then((json) => {
console.log(file.name);
var cursorPosition = this.quill.getSelection();
Take also a look here, to see the differences between function(){} and (args..) => {}
Working on a requirement to upload images to AWS instance. UI and service is separated and connects via REST. Service is in nodejs. from UI we are making a ajax call to backend service to upload the images to AWS.
The problem:
When I upload the images via POSTMAN request, I can see that response as uploaded with files properly uploaded in AWS.
Whereas when I upload images via AJAX call, I get no response in browser, and also the images are not uploaded in aws.
Below is the piece of code in ajax:
var formData = new FormData();
formData.append('image', $('#tx_file_programa')[0]);
$.ajax({
method: 'POST',
type: "POST",
url: 'http://10.0.0.95:9999/photo/1',
contentType: false,
processData: false,
async: false,
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token );
},
data: formData,
success: function (data) {
console.log('response from server is : ', data);
}
//dataType: 'json'
});
This is the backend service.
server.post('/photo/:count', function (req, res) {
if (req.getContentType() == 'multipart/form-data') {
var form = new formidable.IncomingForm(),
files = [], fields = [];
var result = [];
var noOfFiles = req.params.count;
var count = 0;
console.log('noOfFiles', noOfFiles);
form.on('field', function(field, value) {
fields.push([field, value]);
console.log(fields);
})
form.on('progress', function(bytesReceived, bytesExpected) {
console.log('err');
});
form.on('error', function(err) {
console.log('err',err);
});
form.on('aborted', function() {
console.log('aborted', arguments);
});
new Promise(function(resolve, reject) {
var result = [];
form.onPart = function (part) {
var data = null;
const params = {
Bucket: 'xxxxx',
Key: uuidv4() + part.filename,
ACL: 'public-read'
};
var upload = s3Stream.upload(params);
upload.on('error', function (error) {
console.log('errr', error);
});
upload.on('part', function (details) {
console.log('part', details);
});
upload.on('uploaded', function (details) {
let extension = details.Location.split('.');
if(['JPG', 'PNG'].indexOf(extension[extension.length - 1].toUpperCase()) > -1) {
var ext = extension[extension.length - 1];
count++;
result.push(details.Location);
if(count == noOfFiles) {
resolve(result);
}
}
});
part.pipe(upload);
}
}).then(function(result){
console.log('end', result);
res.writeHead(200, {'content-type': 'text/plain'});
res.end('received files:\n\n ' + util.inspect(result));
})
form.parse(req, function (err, fields, files) {
})
return;
} else {
BadRequestResponse(res, "Invalid request type!");
}
})
#user3336194, Can you check with this, this is working thins
var appIconFormData = null
$(":file").change(function () {
var file = this.files[0], name = file.name, size = file.size, type = file.type;
var imageType = new Array("image/png", "image/jpeg", "image/gif", "image/bmp");
if (jQuery.inArray(type, imageType) == -1) {
return false;
} else {
appIconFormData = new FormData();
appIconFormData.append('appimage', $('input[type=file]')[0].files[0]);
}
});
$.ajax({
url: 'your/api/destination/url',
type: 'POST',
data: appIconFormData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data)
},
error: function (e) {
}
});
I think the way you are sending formdata is not correct.
Try these 2 ways:
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
I have this factory:
I'm basically trying to get a file to my server. And when I finish uploading it, I want it to return an answer.
.factory('fileUpload', function($http)
{
var ofileUpload = {};
ofileUpload.uploadFileToUrl = function(file, uploadUrl)
{
var fd = new FormData();
fd.append('file', file);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
,function(){
ofileUpload.answer="success";
ofileUpload.respuesta;
},function(){
ofileUpload.answer="failure";
ofileUpload.answer;
};
}
return ofileUpload;
})
In my controller I am trying to do this:
//I am executting this:
fileUpload.uploadFileToUrl(file, uploadUrl).then(function(){
console.log(fileUpload.answer)
});
but this error appears to me.
TypeError: fileUpload.uploadFileToUrl(...).then is not a function
How can I have my .factory return the response on a promise to receive the value returned (ofileUpload.answer) in my controller?
I solved that. thank you!
.factory('fileUpload', function($http)
{
var ofileUpload = {};
ofileUpload.uploadFileToUrl = function(file, uploadUrl)
{
var fd = new FormData();
fd.append('file', file);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(data) {
ofileUpload.answer="success";
},function(response) {
ofileUpload.answer="failure";
});
}
return ofileUpload;
})
I have to upload image using rest api for successfull upload will get the response of file folder destination ex: D:/ddd/download,I am not able to upload image, below is my code given suggest me any corrections. while uploading image i have to give parameter name as fileData.
api ex: http://somelink and parameter for post is fileData
Html code
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
my service and directive
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
my controller file
$scope.uploadFile = function(){
var data={
'fileData':$scope.myFile
}
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(data, uploadUrl).success(function(response) {
$scope.fileName=response;
})
};
Please check on this...
Controller:
$scope.uploadFile = function () {
var file = $scope.myFile;
console.log(file);
if(file.type==='image/jpeg' || file.type==='image/jpg' || file.type==='image/png' ){
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(file, uploadUrl);
angular.element('input[type="file"]').val(null);
}else{
$scope.errorMessage='File Type Error';
}
};
Service:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, url) {
var uploadUrl = url;
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
console.log("Image Save");
})
.error(function () {
});
};
}]);
You want to pass a the file itself to the formdata object
fileUpload.uploadFileToUrl($scope.myFile, uploadUrl).success(function(response) {
$scope.fileName=response;
})
and set the first parameter of append as fileData
fd.append('fileData', file);
Hi friends now the image upload is working, i have removed service and done changes to my controller by adding below code.
var file = $scope.myFile;
var uploadUrl = "http://";
var fd = new FormData();
fd.append('fileData', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
$rootScope.fileValue = response;
})
i have an angular ui and grails as end points, i posted the files it went ok, but grails seems can't read it.
my angular codes
function sendComment(comment, cb, cbError,token) {
//var promise = $q.defer();
var formData = new FormData();
formData.append('email', comment.email);
formData.append('PNR', comment.PNR);
formData.append('content', comment.content);
formData.append('commentFile',file);
var req = {
method: 'POST',
url: ENV.baseurl +"api/addComment",
transformRequest: angular.identity,
headers: {
'Accept': "application/json",
'Content-Type': undefined,
'Authorization': 'Bearer '+token,
},
data:formData,
}
$http(req).success(cb).error(cbError);
}
my chrome log is
my grails end point
def addComment() {
Comment comment =new Comment()
JSONObject respond = new JSONObject()
comment.content = params.content
comment.PNR = params.PNR
comment.email = params.email
def file = request.getFile('commentFile')
comment.person = Person.findByEmail(params.email);
print file
if (comment.save(flush: true)) {
if (!file) {
CommentFiles files = new CommentFiles()
files.files = new File(file)
files.contentType = uploadedFile.contentType
files.comment = comment
files.save(flush: true)
}
respond.error = false;
respond.message = "comment saved";
response.status = 201;
} else {
print comment.errors.allErrors
respond.error = true;
respond.message = "Could not save comment";
response.status = 409;
}
}
the endpoint have a CORS Interceptor in it, but i'm not 100% sure
please help thanks!
Try without transformRequest: angular.identity,
thanks James Kleeh