ng-file-upload : send List as additional data - angularjs

I want to upload a file using ng-file-upload, and send at the same time a list of values (type Long).
I have done that:
Client side
vm.uploadFiles = function(file, errFiles) {
$scope.f = file;
$scope.errFile = errFiles && errFiles[0];
if (file) {
file.upload = Upload.upload({
url: '/api/sendMailCra',
fields: {'collaborateursId':vm.collaborateursId},
file: file
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
vm.clear();
}, function (evt) {
});
}
}
Server side
#RequestMapping(value = "/sendMailCra",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public void upload(#RequestParam("collaborateursId") List<Long> collaborateursId, #RequestParam("file") MultipartFile file) throws IOException {
log.debug("REST send mail to Collaborateurs : {}"+collaborateursId);
}
I am getting a
500 Internal server error
with no error log on server side.
How can I pass my List from client to server side?
Thanks

By using form data we can send File and data from angular-controller to server.
vm.uploadFiles = function(file, errFiles) {
$scope.f = file;
$scope.errFile = errFiles && errFiles[0];
var data = new FormData();
data.append("uploadFile ", file);
data.append("collaborateursId ", vm.collaborateursId);
if (file) {
file.upload = Upload.upload({
url: '/api/sendMailCra',
data:data,
headers: {'Content-Type': undefined}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
vm.clear();
}, function (evt) {
});
}
}
In Controller using mutipartRequest
#RequestMapping(value = "/sendMailCra",
method = RequestMethod.POST,
)
#Timed
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
String collaborateursId= request.getParameter("collaborateursId");
next converted the request to multipartRequest for get th file
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Iterator<String> fileNames = mRequest.getFileNames();
while (fileNames.hasNext()) {
// HashMap<String, String> hashMap = new HashMap<String, String> ();
MultipartFile file = mRequest.getFile(fileNames.next());
store file into your prefered location....
}
log.debug("REST send mail to Collaborateurs : {}"+collaborateursId);
}
We can set File size limit in the spring configurationFile link
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<beans:property name="maxUploadSize" value="100000" />
</beans:bean>
see this link

Related

asp.net 415 Unsupported Media Type with formData POST

Problem :
API controller cannot access HTTP request data which are included FormData object in HTTP request
I need to pass file object data appended in FormData Object in http Post request to asp.net api controller and front-end is angularjs.i can not retrieve http request data from api controller.my code is below. please look into this, it would be great :)
when i pass,
Content-type : undefined
the error says 415 Unsupported Media Type
if Content-type: multipart/form-data then cannot access data from API controller.
Front-end
$scope.submit = function (files) {
var formData = new FormData();
var getFormData = function(appendFiles){
if (appendFiles.length) {
angular.forEach(appendFiles,function(file){
if(!file.uploaded){
formData.append("imgFiles",file);
file.uploaded = true;
}
});
} else {
formData.append('imgFiles', files);
}
console.log(formData.values());
return formData;
}
$http({
url : "URL",
method: "POST",
data: getFormData(files),
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity,
})
.then(
function (resp) {
// alert(JSON.stringify(resp));
console.log(resp)
},
function (resp) {
console.log(resp)
}
);
};
Api controller Method
[HttpPost]
[Route("route")]
public string UploadFiles(List<HttpPostedFileBase> files)
{
var filesToDelete = HttpContext.Current.Request.Files;
//i need to access file here.using param or otherway
return stat;
}
I have solved the problem.i have changed the api controller method as below,
[HttpPost]
[Route("route")]
public async Task<string> UploadFiles()
{
FileUploadService fileService = new FileUploadService();
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
var uploadFolder = "upload folder physical path"
//this method is in below
var provider = GetMultipartProvider(uploadFolder);
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData fileData in provider.FileData)
{
var physicalPath = fileData.LocalFileName;
var fileName = fileData.Headers.ContentDisposition.FileName;
}
return "return value";
}
private MultipartFormDataStreamProvider GetMultipartProvider(string uploadFolder)
{
try
{
var root = HttpContext.Current.Server.MapPath(uploadFolder);
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
return new MultipartFormDataStreamProvider(root);
}
catch (Exception ex)
{
throw ex;
}
}

Upload Image from angularjs using Springboot to FTP

I am trying to pick a file and upload it to FTP.
For now I get the a 415 (media type unsupported) error when consuming springboot service in angularjs when sending the image.
This is my angular controller:
Controllers.controller('UploadCtrl', [ '$scope', '$http',
function($scope, $http) {
$scope.doUploadFile = function() {
var file = $scope.uploadedFile;
var url = "/ui/upload";
var data = new FormData();
data.append('uploadfile', file);
var config = {
transformRequest : angular.identity,
transformResponse : angular.identity,
headers : {
'Content-Type' : undefined
}
}
$http.post(url, data, config).then(function(response) {
$scope.uploadResult = response.data;
}, function(response) {
$scope.uploadResult = response.data;
});
};
} ]);
My Service Controller JAVA:
#POST
#Path("/upload")
#Consumes("multipart/form-data")
public String upload(#RequestParam("uploadfile") MultipartFile file) throws Exception {
try {
return "You successfully uploaded - " + file.getOriginalFilename();
} catch (Exception e) {
throw new Exception("FAIL! Maybe You had uploaded the file before or the file's size > 500KB");
}
}
For now just getting the file name. What am 'I doing wrong when consuming the POST ?
Thank you in advance
try this:-
HTML
<img ng-src="{{profilePicturePath}}" class="img-responsive"
alt="Image Not found" style="height:150px; width: 150px;">
<input type="file" class="form-control" style="display: none;"
file-model="profileFile" multiple name="profileFile"
id="profileFile" accept="image/*"/>
JS
$scope.profileFile = null;
$scope.$watch('profileFile', function (profileFile) {
if (profileFile && profileFile.name) {
if (profileFile.size / 1012 < 512) {
if (profileFile.type.startsWith("image/")) {
uploadProfilePicture(profileFile);
}
}
}
});
function uploadProfilePicture(profileFile) {
aspirantService.uploadProfilePicture(profileFile).then(function (response) {
getProfilePicturePath();
});
}
this.uploadProfilePicture = function (file) {
var fd = new FormData();
fd.append("doc", file);
return $http.post(Server.url + 'aspirant/pic/', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
};
and JAVA
#Path("pic")
#POST
#Consumes(MediaType.WILDCARD)
public Response uploadProfilePicture(MultipartFormDataInput input, #Context UserSession session) {
for (Map.Entry<String, List<InputPart>> entry : input.getFormDataMap().entrySet()) {
List<InputPart> list = entry.getValue();
for (Iterator<InputPart> it = list.iterator(); it.hasNext();) {
InputPart inputPart = it.next();
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
String fileName = RequestHeaderInfo.getFileName(header);
String contentType = RequestHeaderInfo.getContentType(header);
InputStream inputStream = inputPart.getBody(InputStream.class, null);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
//here code for write file
return Response.ok(proxy).build();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error while getting document!", ex);
}
}
}
return Response.ok().build();
}

file not binding to angularjs service using FormData

I am trying to upload a file using angularjs and spring 3, I have written a service which is not binding the selected file. I don't know what mistake I have been doing, please help me to solve this problem. I am using commonsmultipart for uploading the files. following are the fileUploadService and controller codes.
MyApp.service('fileUploadService', function ($http, $q) {
this.uploadFileToUrl = function (file, uploadUrl, formData) {
//FormData, object of key/value pair for form fields and values
var fileFormData = new FormData();
fileFormData.append('fileUpload', file);
// console.log(formData);
fileFormData.append('name', formData.name);
fileFormData.append('email', formData.email);
fileFormData.append('password', formData.password);
fileFormData.append('mobile_no', formData.mobile_no);
fileFormData.append('register-submit', 'Register Now');
var deffered = $q.defer();
$http.post(uploadUrl, fileFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (response) {
deffered.resolve(response);
}).error(function (response) {
deffered.reject(response);
});
return deffered.promise;
}
});
Spring Controller:
#SuppressWarnings({ "unused", "static-access" })
#RequestMapping( value="/RegisterCandidate" , method = RequestMethod.POST)
private String RegisterCandidate(HttpServletRequest request,
HttpServletResponse response,
#RequestParam CommonsMultipartFile[] fileUpload ) throws Exception{
System.out.println("In method");
String email = request.getParameter("email");
System.out.println("email==============="+email);
String Password = request.getParameter("password");
String usr_name = request.getParameter("name");
String mobile_no = request.getParameter("mobile_no");
Date dateentry = new Date();
java.sql.Timestamp entry_date = new Timestamp(dateentry.getTime());
Users_Pojo usr = new Users_Pojo();
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
usr.setFilename(aFile.getOriginalFilename());
usr.setFile_data(aFile.getBytes());
System.out.println("aFile.getBytes()======"+aFile.getBytes());
System.out.println("aFile.getInputStream()======"+aFile.getInputStream());
System.out.println("aFile.getStorageDescription()======"+aFile.getStorageDescription());
System.out.println("aFile.getSize();======"+aFile.getSize());
System.out.println("aFile.getContentType();==="+aFile.getContentType());/* */
}
}
MD5CodeGenerator md5 = new MD5CodeGenerator();
usr.setUc_password(md5.convertToMD5(Password));
usr.setUc_name(email);
usr.setUc_contact_person(email);
usr.setUc_phone_no(BigInteger.valueOf(Long.parseLong(mobile_no)));
usr.setUc_email_id(email);
usr.setUc_type_id(1);
usr.setUc_active(1);
usr.setValid_from(null);
usr.setValid_to(null);
usr.setDesignation("jobseekar");
usr.setIp_address("164.100.19.79");
usr.setUser_location(1);
usr.setEntry_date(entry_date);
scm_service.save(usr, email);
return "success";
}

Unable send excel file data to web api

In my angular app , I am trying to upload an excel file to web api from Angular JS but I am unable to do so .
The method in the server web api is not being hit.
The angular code looks like :
$scope.file = null;
//UPLOAD FILE CODE
var formdata;
$scope.getTheFiles = function ($files) {
console.log($files[0].type);
formdata = new FormData();
angular.forEach($files, function (value, key) {
formdata.append(key, value);
});
};
// NOW UPLOAD THE FILES.
$scope.uploadFiles = function () {
var request = {
method: 'POST',
url: BasePath + 'uploadNative/UploadFiles/',
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
console.log(formdata);
if (formdata != null || formdata != undefined) {
$http(request)
.success(function (response) {
if (response != "Failed!") {
console.log("Succeeds");
}
else {
console.log("Failed");
}
})
.error(function () {
});
}
And the UI MVC controller which should invoke the web api controller causes exception.
public async Task<JsonResult> UploadFiles()
{
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
string url = BaseURL + "api/Upload/groupmembershipupload/";
string res = await Models.Resource.PostFileAsync(url, Token, hfc, ClientID);
var result = (new JavaScriptSerializer()).DeserializeObject(res);
return Json(result);
}
This PostFileAsync fires the exception.
using (client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthToken);
client.DefaultRequestHeaders.Add("ClientID", ClientID);
var content = new MultipartFormDataContent();
System.Web.HttpPostedFile hpf = data[0];
byte[] fileData = null;
using (var sds = new BinaryReader(hpf.InputStream))
{
fileData = sds.ReadBytes(hpf.ContentLength);
}
content.Add(new ByteArrayContent(fileData, 0, fileData.Count()));
//using (response = await client.PostAsJsonAsync(url + "?=" + DateTime.Now.Ticks, data))
using (response = await client.PostAsync(url + "?=" + DateTime.Now.Ticks, content))
{
...the response is Http Error 415 "Unsupported Media Type". It does not call the service.
Change the headers to:
headers: {
'Content-Type': 'multipart/form-data'
}

How to make Spring REST service to accept multipart file data sent by the Angular Controller?

I'm trying to post a file from Angular controller to the backend. But Spring REST controller is receiving null.
JS
myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file", $scope.myFile);
alert("Hi");
$http({
method: 'POST',
url: 'upload',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
console.log('file is ' );
console.dir(data);
})
.error(function(data, status) {
});
}
}]);
Spring-REST Controller
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String upload(#RequestBody MultipartFile file) {
System.out.println(file);
}
I also tried with public #ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) but it's of no use. I have declared multipartResolver in the configuaration file too. Any Idea on this? I'm desperately looking for a solution.
Here is a piece of code that works for me:
Spring-REST Controller
#RequestMapping(value = "/api/users/{id}/image", method = RequestMethod.POST)
#ResponseBody
public boolean uploadUserImage( #PathVariable("id") Long id, #RequestParam("file") MultipartFile file ) {
return userService.saveUserImage(id, file);
}
and on the front-end you could do something like this
Angular Controller
//the image
$scope.uploadme;
$scope.uploadImage = function() {
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.uploadme);
fd.append('file', imgBlob);
$http.post(
'/upload',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function(response) {
console.log('success', response);
})
.error(function(response) {
console.log('error', response);
});
}
//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
Assuming that the http request is correct the problem must be at the Spring controller. I think you have to change upload(#RequestBody MultipartFile file) to upload(#RequestParam("file") MultipartFile file). So it will be like this:
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseBody
public void upload(#RequestParam("file") MultipartFile file) {
System.out.println(file);
}
Also in your function you have it return String but you are not returning one. So i assume you are doing something else and you removed the code in order to post the question and missed the return, otherwise it wouldn't even build.
Lastly you could check this answer that i gave to a similar problem.

Resources