Springboot API, receive file - java

I'm trying to make simple Springbot API that will be receive file from frontend. All tutorials that I found is complex and is too much for me. For educational purpose I just wanna to get file and print name of file.
Code that I tried:
#PostMapping(path="/postFile")
public void postFile(#RequestBody MultipartFile file){
System.out.println(file.getName());
}
Code return that variable file is null, and I don't know what I'm doing wrong.
Code from my frontend
function clickHandler(){
const formData = new FormData();
formData.append('File',selectedFile);
fetch("https://localhost:8443/postFile", {
method: 'POST',
body: formData
})
}

Use #RequestParam("File") instead of #RequestBody. As you are sending a form where your file is bounded to field 'File'.

Related

Some problem Logic with response POST in spring boot

I will have to do some development and I will need your logic please,
I'll try to be as clear as possible
I have a JSON file that will be sent to a Web Service to process it.
When the file arrives on this Web Service, I have to parse it.
First question :
Is it a #PostMapping to recover this file?
Since it's a file, I get it as a file like this:
#PostMapping( value="/getFile",
consumes = {"multipart/form-data"})
public void postFile(#RequestParam() MultipartFile file) throws IOException
I recover the file well, but the concern is that the #RequestParam parameter expects a file name, except that when the file is sent to the web service, I do not know its name yet,
Second Question :
So how do you parse this file into a string?
Thank you in advance for your precious help
For the first question:
Yep, #PostMapping is the right way to go. Regarding the file name bit, #RequestParam() does not expect the file name to be passed, it expects the "key" of the key-value pair where the value is the file being uploaded.
For example, when sending a file via a RestTemplate call, the file would be included in the POST call as somewhat like this:
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("uploadFile", getFileToUpload());
Here the key is "uploadFile", so your controller will look like this :
#PostMapping( value="/getFile",
consumes = {"multipart/form-data"})
public void postFile(#RequestParam("uploadFile") MultipartFile file) throws IOException
Checkout this tutorial : https://spring.io/guides/gs/uploading-files/
For the second question:
ByteArrayInputStream stream = new ByteArrayInputStream(file.getBytes());
String myFileString = IOUtils.toString(stream, StandardCharsets.UTF_8);
This should do. Cheers

how to upload excel file using Java Restful web services and AngularJS

I want to take Excel file from html input type="file" and pass that Excel file to my rest method java by http post method. I have a angular controller for that. I want to know how the controller should look like and what should be there in my rest method. I am using Apache POI to process the excel file.
You can have a angular method like this:
$scope.exelMethod = function (){
var excelObj = {};
excelObj.name = 'test';
excelObj.age = '20';
//you can write '/excel' as a rest web-service
$http.post('/excel,excelObj).success(function(response) {
console.log(response);// This will be a download path
//after this call the download function
});
}
In the middle layer you can write /excel service and map the excelObj from front end to a class view like this
public class ExcelView{
private String name;
private String age;
}
Now you can use this ExcelView class to map your data using POI. You will have to process the data and pass a download location of the file in the server to FE. In FE you will have to write a download function to download the file from the path you just got from the response.
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response getExcelData(ExcelView excelObj)
{ //this will be the service
}
if you need to know hot to write excel using poi check out this link
http://www.avajava.com/tutorials/lessons/how-do-i-write-to-an-excel-file-using-poi.html

How to upload a file and JSON data in Postman?

I am using Spring MVC and this is my method:
/**
* Upload single file using Spring Controller.
*/
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(
#RequestParam("name") String name,
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpServletResponse response) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists()) {
dir.mkdirs();
}
// Create the file on server
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location=" + serverFile.getAbsolutePath());
return null;
} catch (Exception e) {
return null;
}
}
}
I need to pass the session id in postman and also the file. How can I do that?
In postman, set method type to POST.
Then select
Body -> form-data -> Enter your parameter name (file according to your code)
On the right side of the Key field, while hovering your mouse over it, there is a dropdown menu to select between Text/File. Select File, then a "Select Files" button will appear in the Value field.
For rest of "text" based parameters, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.
The Missing Visual Guide
You must first find the nearly-invisible pale-grey-on-white dropdown for File which is the magic key that unlocks the Choose Files button.
After you choose POST, then choose Body->form-data, then find the File dropdown, and then choose 'File', only then will the 'Choose Files' button magically appear:
Maybe you could do it this way:
Like this :
Body -> form-data -> select file
You must write "file" instead of "name"
Also you can send JSON data from Body -> raw field. (Just paste JSON string)
I got confused after seeing all of the answers, I couldn't find any proper screenshot to bring the Content Type column. After some time, I found it by my own. Hope this will help somebody like me.
Here is the steps:
click on red marked area of postman.
Now check the green marked option (Content Type).
Now change the search content type, in the yellow marked area.
In my case:
invoice_id_ls (key) contains the json data.
documents contains the file data.
placed_amount contains normal text string.
Select [Content Type] from [SHOW COLUMNS] then set content-type of "application/json" to the parameter of json text.
Don't give any headers.
Put your json data inside a .json file.
Select your both files one is your .txt file and other is .json file
for your request param keys.
If somebody wants to send json data in form-data format just need to declare the variables like this
Postman:
As you see, the description parameter will be in basic json format, result of that:
{ description: { spanish: 'hola', english: 'hello' } }
Kindly follow steps from top to bottom as shown in below image.
At third step you will find dropdown of type selection as shown in below image
Body > binary > Select File
If you need like
Upload file in multipart using form data and send json data(Dto object) in same POST Request
Get yor JSON object as String in Controller and make it Deserialize by adding this line
ContactDto contactDto = new ObjectMapper().readValue(yourJSONString, ContactDto.class);
If somebody needed:
body -> form-data
Add field name as array
Use below code in spring rest side :
#PostMapping(value = Constant.API_INITIAL + "/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file,String jsonFileVo) {
FileUploadVo fileUploadVo = null;
try {
fileUploadVo = new ObjectMapper().readValue(jsonFileVo, FileUploadVo.class);
} catch (Exception e) {
e.printStackTrace();
}
If you want to make a PUT request, just do everything as a POST request but add _method => PUT to your form-data parameters.
The way to send mulitpart data which containts a file with the json data is the following, we need to set the content-type of the respective json key fields to 'application/json' in the postman body tab like the following:
You can send both Image and optional/mandatory parameters.
In postman, there is Params tab.
I needed to pass both: a file and an integer. I did it this way:
needed to pass a file to upload:
did it as per Sumit's answer.
Request type : POST
Body -> form-data
under the heading KEY, entered the name of the variable ('file' in my backend code).
in the backend:
file = request.files['file']
Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.
2.
needed to pass an integer:
went to:
Params
entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE
in the backend:
id = request.args.get('id')
Worked!
For each form data key you can set Content-Type, there is a postman button on the right to add the Content-Type column, and you don't have to parse a json from a string inside your Controller.
first, set post in method and fill link API
Then select Body -> form-data -> Enter your parameter name (file according to your code)
If you are using cookies to keep session, you can use interceptor to share cookies from browser to postman.
Also to upload a file you can use form-data tab under body tab on postman, In which you can provide data in key-value format and for each key you can select the type of value text/file. when you select file type option appeared to upload the file.
If you want the Id and File in one object you can add your request object to a method as standard and then within Postman set the Body to form-data and prefix your keys with your request object name. e.g. request.SessionId and request.File.
The steps of uploading a file through postman along with passing some input data is very well discussed in below blog along with the screenshot. In this blog, the api code is written in node js. You can go through it once to have more clarity.
https://jksnu.blogspot.com/2021/09/how-to-create-post-request-with.html
At Back-end part
Rest service in Controller will have mixed #RequestPart and MultipartFile to serve such Multipart + JSON request.
#RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
#ResponseBody
public boolean yourEndpointMethod(
#RequestPart("properties") #Valid ConnectionProperties properties,
#RequestPart("file") #Valid #NotNull #NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
At front-end :
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
See in the image (POSTMAN request):
Click to view Postman request in form data for both file and json
To send image along with json data in postman you just have to follow the below steps .
Make your method to post in postman
go to the body section and click on form-data
provide your field name select file from the dropdown list as shown below
you can also provide your other fields .
now just write your image storing code in your controller as shown below .
postman :
my controller :
public function sendImage(Request $request)
{
$image=new ImgUpload;
if($request->hasfile('image'))
{
$file=$request->file('image');
$extension=$file->getClientOriginalExtension();
$filename=time().'.'.$extension;
$file->move('public/upload/userimg/',$filename);
$image->image=$filename;
}
else
{
return $request;
$image->image='';
}
$image->save();
return response()->json(['response'=>['code'=>'200','message'=>'image uploaded successfull']]);
}
That's it hope it will help you

How to filter responses types in HtmlUnit?

While crawling a webpage I am getting various response types (image/text/html/json/css/js etc). I only need the .json files not the other ones. How can I filter other response types using HtmlUnit?
Problem is: The required data is stored in a specific .json file and that .json file doesn't have a unique url. So I am planning to filter other response type and download the content of all the json files. Later on I will clean the data.
Please help. Just an idea will be enough.
You can see modify the request and responses, as hinted here.
Check if the URL contains .json string, and then save it.
new WebConnectionWrapper(webClient) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if (request.getUrl().toExternalForm().contains(".json")) {
String content = response.getContentAsString("UTF-8");
//save content
}
return response;
}
};

How To Download PDF file using Jersey?

I need to download pdf file using Jersey Web Services
i already do the following but the file size received is always 0 (zero).
#Produces({"application/pdf"})
#GET
#Path("/pdfsample")
public Response getPDF() {
File f = new File("D:/Reports/Output/Testing.pdf");
return Response.ok(f, "application/pdf").build();
}
Please help to do the correct way, thanks !!
Mkyong always delivers. Looks like the only thing you are missing is the correct response header.
http://www.mkyong.com/webservices/jax-rs/download-excel-file-from-jax-rs/
#GET
#Path("/get")
#Produces("application/pdf")
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=test.pdf");
return response.build();
}
You can't just give a File as the entity, it doesn't work like that.
You need to read the file yourself and give the data (as a byte[]) as the entity.
Edit:
You might also want to look at streaming the output. This has two advantages; 1) it allows you to use serve files without the memory overhead of having to read the whole file and 2) it starts sending data to the client straight away without you having to read the whole file first. See https://stackoverflow.com/a/3503704/443515 for an example of streaming.
For future visitors,
This will find the blob located at the passed ID and return it as a PDF document in the browser(assuming it's a pdf stored in the database):
#Path("Download/{id}")
#GET
#Produces("application/pdf")
public Response getPDF(#PathParam("id") Long id) throws Exception {
Entity entity = em.find(ClientCase.class, id);
return Response
.ok()
.type("application/pdf")
.entity(entity.getDocument())
.build();
}

Categories

Resources