Unable to upload file to attachment table from portal widget, any help ?

Snehal13
Kilo Sage

From Portal widget, I have file upload option and button to upload the file. Upon click of this button, it must create record in attachment table and attach the file to this new record.

 

What is wrong in below code ? Unable to upload file to attachment table.

 

HTML

  <div>
<br>  File: <input type="file" id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)">
<br>	   
  
<input type="button" ng-click="uploadFiles()" value="Upload"></div>

Server script

(function() {
data.response = '';
	
		var gr = new GlideRecord('sys_attachment'); //input.table
		gr.insert();
		//how to upload file during insert
	

})();

Client controller

api.controller=function($scope) {
var c = this;
// CODE FOR sn-record-picker
  $scope.tableName = {
    name: 'sys_attachment'
  };		
  $scope.$on("field.change", function(evt, parms) {
    if (parms.field.name == 'tableName'){
			c.data.table = parms.newValue.toString();
			c.server.update();
		}
	});

// CODE FOR input	record
  $scope.getID = function(rec) {
		c.data.record = rec.toString();
    c.server.update();
  };
	
// CODE FOR fileupload	
	/*$scope.files = [];	
	$scope.setFiles = function(element) {
		$scope.$apply(function() {
			
			// Turn the FileList object into an Array
			for (var i = 0; i < element.files.length; i++) {
				$scope.files.push(element.files[i]);
			}
		});
	};
	
	$scope.removeFiles = function(fname) {
		var index = $scope.files.indexOf(fname);
		if(index>-1)
			$scope.files.splice(index,1);
	};	*/

	$scope.uploadFiles = function() {
		alert("Trying to upload file");	
		$scope.fd = new FormData();
		$scope.files.forEach(function(file){
			$scope.fd.set('files', file);
			var request = {
				method: 'POST',
				url: 'https://dev23367.service-now.com/api/now/attachment/file?table_name='+c.data.table+'&amp;table_sys_id='+c.data.rec_sysid+'&amp;file_name='+file.name,
				data: $scope.fd.get('files'),
				headers: {
					'Content-Type': file.type,
					'Accept':'application/pdf'					
				}
			};
			

			// SEND THE FILES.
			$http(request)
				.success(function (d) {
				alert("Uploaded with success");
			})
				.error(function (err) {
				alert("Error");
			});

		});
	}
};

 

1 REPLY 1

Reddy
Kilo Sage

@Snehal13I'm working on a similar requirement. Did you implement this? If yes, could you please share the script with me?