Image upload with angularjs and spring boot - angularjs

I'm trying to upload an image from an angularjs application to a Spring Boot endpoint, but I'm having the problem below:
{"timestamp":1522031262882,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'image' is not present","path":"/customer/uploadLogo"}
Angularjs code:
function uploadLogo(formdata) {
var formData = new FormData();
formData.append('image', $scope.picture);
return $http.post(defaultConfig.baseUrl + 'customer/uploadLogo', formdata, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
});
}
Spring-boot code:
#PostMapping(path = "/uploadLogo")
public void uploadLogo(#RequestParam("image") MultipartFile file) {
System.out.println("");
}
I'm passing "image" on formData, so this exception does not make much sense to me. Has anyone ever had anything like this?

Related

can i send form-data with axios with delete request in react?

i need send this request with axios.
i need header as multipart request, like below
headers: {
"Content-type": "multipart/form-data",
},
I used spring boot for backend. It expect maltipart not application/json. I tried below code, But it not worked for multipart.
axios.delete(URL, {
headers: {
Authorization: authorizationToken
},
data: {
source: source
}
});
Thanks a lot #Sinan Yaman. I generated it using POSTMAN. Answer is
var axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('keyName', 'project/photoes/1613388881570-note1.txt');
var config = {
method: 'delete',
url: 'localhost:8080/storage/deleteFile',
headers: {
...data.getHeaders()
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Typically before make frontend we test our backend with postman. For any type of frontend http calls code can automatically generate using postman. This is awesome feature of POSTMAN. Follow below steps.
Press the code button
Select the your backend code environment

File Upload using spring rest and axios, no multipart boundary was found

I have some issues in file uploading using spring rest and react and axios,
my back-end code is
#PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity uploadFile(#RequestParam MultipartFile file) {
return ResponseEntity.ok().build();
}
and I can upload file using postman, but by using axios I got some errors.
nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
here is my code:
let formData = new FormData();
formData.append("file", this.state.selectedFile);
axios({
method: "post",
url: url,
data: {
formData
}
})
also if I put
headers: { "Content-Type": "multipart/form-data" }
I got error too,
can anyone tell me what are my mistakes please?
It may be beacause you are creating a new object and sending the data inside the object
Try this data: formData
let formData = new FormData();
formData.append("file", this.state.selectedFile);
axios({
method: "post",
url: url,
data: { formData},
{...axios.default.headers,
...{headers: { "Content-Type": "multipart/form-data" }}
}
})
You dont need to put any headers as it will automatically , decides the parameters of headers , when you do it manually you need to explicitly decides few parameters which is quite difficult to judge , so dont give headers

Uploading document from angularjs to springboot

Angularjs $http.post gives a 404 exception but all the other methods works fine with the same codes, i am trying to upload a file via spring boot
The same codes works fine in my other project i did about last year, and the same $http.post works when i send information without a file
service.js
function addCompanyDoc(file, id) {
var deferred = $q.defer();
var data = new FormData();
data.append('file', file);
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
console.log('appService file ');
console.dir(file); //cheking if file is available
$http.post('http://localhost:8080/listed/welcome/company/doc/' + id,
data, config)
.then(function(response) {
deferred.resolve(response.data);
},
function(errResponse) {
alert(errResponse.data.errorMessage);
console.error('Error while uploading company doc', errResponse);
this.flag = 'failed';
deferred.reject(errResponse);
});
return deferred.promise;
}
spring boot
#RequestMapping("/welcome")
public class controllers{
#RequestMapping(value = "/company/doc/{id}", method =
RequestMethod.POST, consumes = {"multipart/form-data" })
#ResponseBody
public ResponseEntity<Void> saveCompanyDoc(#RequestParam("file")
MultipartFile file, #PathVariable final int id){
//....uploading to DB
}
}
angularjs sends a document to spring boot and spring uploads to the DB / sends to a folder.
Working fine :-) with angularjs 1.7 & spring boot 2.*
Thanks for all the comments the above code is correct,
I created a dummy table and controller to test the app.
And it gave the same 404 error and i recalled a few weeks back i added an "admin folder" to handle CMS and directed all the ROLES to the "folder" and it blocked all the users from doing data POSTING. SO i just had to fix my WebSecurityConfig class :-)

File upload fails with angularjs and spring boot

I want to upload file
controller.js
userService.saveProfile($scope.user.profile.companyLogo).then(function(response){
if(response.status==201){
$('#profileModal').hide();
$scope.load();
}
});
service.js
saveProfile:function(logo){
var formData = new FormData();
formData.append("file",logo);
var retVal = $http({
method : 'POST',
url : '/api/user/profile',
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
data: formData
}).then(function(response){
return response;
});
return retVal;
}
Controller.java
#RequestMapping(value="/profile",method = RequestMethod.POST,headers="'Content-Type':'multipart/form-data'")
public ResponseEntity saveProfile(#RequestBody MultipartFile file){
System.out.println(file);
return new ResponseEntity(HttpStatus.CREATED);
}
if I add headers to #RequestMapping I'm getting 404 and if I remove it I'm getting file null
Please suggest me the correct way of doing file upload
It worked!
I removed headers from #RequestMapping and used #RequestPart instead of #RequestBody
#RequestMapping(value="/profile",method = RequestMethod.POST)
public ResponseEntity saveProfile(#RequestPart("file") MultipartFile file){
System.out.println(file);
return new ResponseEntity(HttpStatus.CREATED);
}

MissingServletRequestPartException: Required request part 'file' is not present

I've been looking at this but it seems my problem is elsewhere. I am trying to upload a file. The input is currently defined as:
<input
type="file"
style="display: none;"
name="file"
multiple
nv-file-select
uploader="uploader">
This is how the upload is performed:
var uploader = $scope.uploader = new FileUploader({
url: 'http://localhost:8080/rest-api/dl4j/we/uploadModel'
});
uploader.onAfterAddingFile = function($modelFile) {
var fd = new FormData();
fd.append('file', $modelFile.file);
$http.post($modelFile.url, fd, {
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
})
.then(
function (data) {
alert("upload success");
},
function (data, status) {
alert("upload error");
}
);
};
Whereas this is the Spring REST endpoint:
#PostMapping(WordEmbeddingApiPaths.UPLOAD_MODEL)
#RequestMapping(method=RequestMethod.POST, headers={"Content-Type=multipart/form-data"})
public ResponseEntity<WordVectorListDto> uploadModel(
#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
LOGGER.debug("POST uploadModel");
return new ResponseEntity<WordVectorListDto>((WordVectorListDto)null, HttpStatus.OK);
}
The problem is though, that an exception is getting thrown by Spring, telling me that the parameter file is not present:
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present
This is the request information:
How can I make this file upload work?
I guess it can be related to the content type
In your code i see this:
$http.post($modelFile.url, fd, {
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
})
So you are defining an undefined content-type; You should set multipart/form-data
Try to put this content-type
I hope it's usefull
Angelo

Resources