I have an endpoint to get the image i uploaded earlier, it works but not well
I don't know if i can get the image in response
my controller endpoint:
#PreAuthorize("hasAuthority('user:write')")
#GetMapping(value = "{messageId}/files/{file_name}")
public FileSystemResource getFile(#PathVariable("messageId") Integer id,#PathVariable("file_name") String fileName) throws FileNotFoundException {
return new FileSystemResource(messageService.getImage(id,fileName));
}
Response headers:
Postman example to save image
Click on 'Save Response', then 'Save to a file' with the extension you need.
Luck!
Related
I'm making a program that captures webcam images and I need to be able to send them to a backend for text detection and image recognition.
I'm using react webcam for the screenshots. Component is declared like this:
<Webcam
mirrored="false"
audio={false}
screenshotFormat="image/jpeg"
ref={props.webcam}
style={{
marginLeft: "auto",
marginRight: "auto",
display: "block",
paddingTop: "10px",
paddingBottom: "10px",
}}
/>
then, I invoke webcamRef.current.getScreenshot() to get the Image as a Base64 encoding. bytes are sent to a java backend with the following logic:
var formData = new FormData();
formData.append("file", props.image);
formData.append("user", props.user);
axios
.post("http://localhost:8080/api/storeImage", formData, {
headers: { "Content-Type": "multipart/formdata" },
})
.catch((err) => {
throw err;
});
Everything works fine up to this point. Problem arises when I try to create an ImageBuffer from the java backend:
Contoller:
#PostMapping("/api/storeImage")
#ResponseBody
public String storeImage(#RequestParam("file") String file, #RequestParam Long user) throws IOException, InvalidDniException {
return service.storeImage(file, user);
}
Service:
public String storeImage(String source, Long user) throws IOException, InvalidDniException {
byte[] decodedSource = Base64.getMimeDecoder().decode(source);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(decoded)); <-- this returns null ...
I need the BufferedImage to crop and extract information from the captured screenshot. Every answer I've found on similar questions do not seem to work here.
Turns out I had to remove this prefix: data:image/jpeg;base64 from the String received.
Image
I want to write a client code to consume an API. The API is expecting a text file. When I select the binary file option in the postman tool and select any text file from my local it worked. how to implement this in spring ?. I have tried MULTIPART_FORM_DATA but no luck.
If You mean file
#RestController
public class FileContentController {
#RequestMapping(value="/up", method = RequestMethod.POST)
public ResponseEntity<?> upload(#RequestParam("file") MultipartFile file)
throws IOException {
String contentType=file.getContentType());
InputStream i=file.getInputStream();
return new ResponseEntity<>(HttpStatus.OK);
}
return null;
}
also spring boot has multi part confs, you should enable it and set size and tempdir
,In Earlier version spring boot need to add:
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.servlet.multipart.enabled=true
spring.servlet.multipart.location=${java.io.tmpdir}
However in your client code you should not set content-type application/json in your header post request
simple fetch should be such
const input = document.getElementById('uploadInput');
const data = new FormData();
data.append('file', input.files[0]);
var resp = await fetch('upload/', {
method: 'POST',
body: data
});
if (!resp.ok) {
throw new Error(`HTTP error! status: ${resp.status}`);
}
if (resp.ok) {
await this.images();
}
I an creating an endpoint with spring boot...i can upload image to folder and save it via postman everythink works good.
i have a problem with get method when i am adding the value #RequestMapping value = "getImage/{imageName:.+}" in postman i add http://localhost:8080/api/images/getImage/{burger+png}
is that corect ???
#RequestMapping(value = "api/images")
public class ImageController {
#Autowired
public ImageService imageService;
#PostMapping(value ="upload")
public ResponseEntity uploadImage(#RequestParam MultipartFile file){
return this.imageService.uploadToLocalFileSystem(file);
}
#GetMapping(
value = "getImage/{imageName:.+}",
produces = {MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_GIF_VALUE,MediaType.IMAGE_PNG_VALUE}
)
public #ResponseBody byte[] getImageWithMediaType(#PathVariable(name = "imageName") String fileName) throws IOException {
return this.imageService.getImageWithMediaType(fileName);
}
}
what should be the correct request url ???
It seems like it's reaching the backend fine, but failing to find path. Usually API endpoints end with parameters with a slug or query param. You can try either of the following to see if it works:
http://localhost:8080/api/images/getImage/burger.png
http://localhost:8080/api/images/getImage?imageName=burger.png
Keep in mind, you want to make sure that file exists at the path it's mentioning at the very top of the trace in the JSON response. This may depend on how you uploaded the file and with what name.
I am trying to render an image which I got from a Java service as InputStream, re-send it through NodeJS Express server and finally render it in Angular4
Here's what I do:
Java Jersey service:
#GET
#Path("thumbnail")
#ApiOperation(
value = "Gets document preview",
notes = "Gets document preview"
)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Preview of the document")
})
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("image/png")
public Response getDocThumbnail(
#ApiParam(value = "Entity UUID", required = true) #FormDataParam("uuid") String uuid
) throws RepositoryException, UnknowException, WebserviceException, PathNotFoundException, DatabaseException, AutomationException, AccessDeniedException, ConversionException, IOException {
RawDocument rawDocument = docCtrl.getDocThumbnail(uuid);
return Response
.ok(rawDocument.getInputStream(), "image/png")
.header("Content-Disposition", "attachment; filename=\" " + rawDocument.getName() + "\"")
.build();
}
the controller looks like:
public RawDocument getDocThumbnail(String uuid) throws IOException, AccessDeniedException, PathNotFoundException, WebserviceException, RepositoryException, DatabaseException, ConversionException, AutomationException, UnknowException {
return new RawDocument(
okmWebSrv.getOkmService().getThumbnail(uuid, ThumbnailType.THUMBNAIL_LIGHTBOX),
"whatever"
);
}
Basically it's call to OpenKM SDK to retreive document's thumbnail
This Java endpoint is called from NodeJS Express 4.15 that is pre-processing some requests for this Java backend.
Here's what I do:
...compose request options...
const vedica_res = await rp(options);
let buffered = new Buffer(vedica_res, 'binary');
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-disposition': 'attachment;filename=' + 'thumb.png',
'Content-Length': buffered.length
});
return res.end(buffered, 'binary');
Finally with Angular4 being the initiator of this roundtrip I am trying to render the image like so:
this.rest.send('http://localhost:4200/vedica/api/document/thumbnail', RequestMethod.Get,
{uuid: '19516ea1-657e-4b21-8564-0cb87f29b064'}, true).subscribe(img => {
// this.preview = img
var urlCreator = window.URL;
var url = urlCreator.createObjectURL(img);
this.thumb.nativeElement.src = url;
})
The 'img' received is a Blob {size: 81515, type: "image/png"}. Console shows no errors but renders no image in the <img #thumb/> tag. But I can see that it sets the src=blob:http%3A//localhost%3A3000/4cf847d5-5af3-4c5a-acbc-0201e60efdb7 for it. Image just has a broken image icon.
When I try to read a cached response in a new tab, its accessible but renders nothing again.
Can you point out what I'm doing wrong? Have tried a lot, but no luck.
I think the problem is not the stream is closed early, the problem I think will be in the way is downloaded, take a look here:
https://docs.openkm.com/kcenter/view/sdk4j-1.1/document-samples.html#getContent
From the server side ( inde middle between OpenKM and your user interface ) the problem usualy is:
//response.setContentLength(is.available()); // Cause a bug, because at this point InputStream still has not its real size.
And you should use
response.setContentLength(new Long(doc.getActualVersion().getSize()).intValue());
resolved this by replacing request-promise with bare request package for making this request to the java BE and piping reply right into the wrapping response of the angular FE:
let reply = request(options);
reply.pipe(res);
I am trying so much to send a request like CommonsMultipartFile and one java object.I constructed controller like follows.
public #ResponseBody Response upload(#RequestParam CommonsMultipartFile userPhoto, #RequestBody UserDetails userDetailsId,
#RequestParam String authCode)
//method impl
}
when I am trying to send request from postman:
In form-data uploaded image(1st screenshot) ,In Body-raw(2nd screenshot) i am sending user object.This is what I done.Can you please tell me how to fix this issue.Or can you please suggest me right way if I am wrong.
Thanks in advance.
#RequestMapping(method = RequestMethod.POST, headers = ("content-type=multipart/*"), produces = "application/json", consumes = "image/*")
public RestResponse save(#RequestParam("bankAddress") String bankAddress, #RequestParam("bankNameAr") String bankNameAr, #RequestParam("bankNameEn") String bankNameEn, #RequestParam("bankPhone") String bankPhone, #RequestParam("bankStatus") BigDecimal bankStatus, #RequestParam("countryId") long countryId,
#RequestParam("bankImage") MultipartFile file) {
.
.
.
}
and use byte[] data = file.getBytes(); to get file into byte[] and use for further process.