Java Spark REST api upload file - java

I'm working with java using java-spark to create the Rest Api and I'm having trouble figuring out how to receive a file so then I can process it. Haven't found anything as like in Spring that handles MultipartFile. Also this proyect is ran on a Tomcat server.

As per the official documentation, the following code you get you started:
post("/yourUploadPath", (request, response) -> {
request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
try (InputStream is = request.raw().getPart("uploaded_file").getInputStream()) {
// Use the input stream to create a file
}
return "File uploaded";
});

Related

Getting a PDF from another API

How can I get a PDF from another API through my own API then to the front for downloading by the user.
All I get now is a blank page.
The back is in Scala and when I println the file, I get it in a String.
In the front, I get the blob and use that function to download it :
onDownload(invoice) {
var mediaType = 'application/pdf';
this.invoices.downloadInvoice(invoice.id).subscribe((file: Blob) => {
const fileName = invoice.number;
var blob = new Blob([file], { type: mediaType });
const fileUrl = URL.createObjectURL(blob);
FileSaver.default(fileUrl, fileName.toString());
}), err => {
console.error(err);
}
}
The back is using Play and the WebService to get the file from another API but I can only receive it as a string it seems. Should I try to store him on the server then serve it to the front ?
Which scala-server used? And what does the path/API return?
Should I try to store him on the server then serve it to the front
This is the sure-shot way of making it work. For eg: If using akka-server, save the incoming file in some temporary location (say /tmp), and use akka-route getFromFile to server the file to front-end. Every server will have an equivalent of this.
If we want to bypass file-saving, we need to trick/hack the client into thinking that the incoming string is actually a file. I am not sure if your server will allow this, but you can try by passing the same http-headers. For this, create a simple API to send some PDF, check all the headers received on the client side, and then make sure your hacky way sends the same http-headers.

Spring Boot Multipart File Upload - Tips to Improve Performance

I am exposing RESTful API to the reactjs front end application which is used to upload a file to Database.
Server Side Controller Code:
#RequestMapping(value = "/api/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public UploadResponse uploadDocument(#RequestParam("doc") MultipartFile doc,
#RequestParam("metaData") String metaData, HttpServletResponse response) {
// logic to save in DB
return new UploadResponse();
}
Client Side JS Code:
uploadDocument(formData, callback) {
instance.post('/api/upload', formData)
.then((response) => {
callback(response);
})
.catch((error) => {
const errorObj = {
status: error.response.status,
data: {
message: error.response.data.message,
},
};
callback(errorObj);
});
}
application.properties
spring.http.multipart.max-file-size=20MB
spring.http.multipart.max-request-size=20MB
I am trying to upload a 20MB file (CSV or any other) , it is taking too much time to reach the controller side. (~ 1-2 minutes )
Please suggest some good techiniques or tips to improve the performance using same multipart request.
(ex: Chunking or Compressing or Streaming)
I think the easiest way would be to just zip content at javascript side and upload it to you spring boot application.
react js parts: please read upload zip file from reactjs to nodejs
spring boot multipart octet stream handling - necessary classes, test mocks etc. are described at How to go from spring mvc multipartfile into zipinputstream
Using this you should be able to zip content at react side and use it at your spring application.
Or you just zip at react side and upload the file in a normal way without any special octet stream handling in spring boot but just using java zip package classes to unzip files.

Spring Boot serving an m3u8 playlist

I'm trying to serve an m3u8 playlist through Spring Boot. I have a running ffmpeg process that is transcoding a multicast in real-time and sending the files to /src/resources/public/output.m3u8. I see the playlist updating and the new .ts files being generated correctly however when trying to watch the stream in a video player, it only plays a certain amount of video. Is there a way to properly serve up a running playlist in Java instead of serving it statically?
EDIT: When starting a basic http server with python python3 -m http.server, I'm able to view the stream perfectly fine. Is there a Spring Boot way to accomplish the same task?
With Spring 4.1 your approach will work there is no issue in it. Here below is another approach in case if you want to look
#RequestMapping(value = "/VMS-49001/playlist/{listName:.+}")
public ResponseEntity<byte[]> testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"));
headers.setContentDispositionFormData(fileName, fileName);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}

How to read body of HttpServletRequest multiple times?

Basically I need to read the body of HttpServletRequest multiple times, based on my research I found that one of easiest way for doing that is by using ContentCachingRequestWrapper
Here is how I implemented it:
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
try{
MultipartRequest multipartRequest = new MultipartRequest(requestWrapper, ImageDirecoty, 1024*1024*5);
String test = requestWrapper.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
System.out.print(test);
} catch(IOException e){
System.out.println(e.getMessage());
return;
}
FYI: I am uploading a simple file from my client to server.
Now at first it reads the request body just fine, but in the second line which I have String test = requestWrapper to read it's content and to output it to console I don't get my Ecplise console outputing me anything and I don't get any error too, I'd really appreciate if somebody tell me what am i doing wrong.
actually the easy est way to do it is to use(convert the response), to some kind of Pojo class, and then saving it to whatever you want.
here is a link to convert it to pojo
http://www.jsonschema2pojo.org/
also you can use library's like Retrofit 2.0 to make your http calls much easier.
http://square.github.io/retrofit/

IOException when Uploading Videos to YouTube via Java API

I have been attempting to upload videos to YouTube via the JavaAPI using Direct Uploading. I have been having a problem when I call the insert() method, I get a IOException with the error message
"Error writing request body to the server"
I have verified that the File object I am creating is correct as well as all the details in my VideoEntry object. I have been using Fiddler to monitor the activity from my machine and no request is made to the upload API so the problem is not there. Here is a summary of the code I am using:
VideoEntry newVideo = new VideoEntry();
//Defined video properties such as title and description here.
MediaFileSource ms = new MediaFileSource(videoFile, "video/flv");
newVideo.setMediaSource(ms);
VideoEntry createdEntry = settings.insert(new URL(apiUrl), newVideo);
The IOException is thrown on the insert call (settings is my YouTubeService instance) and the API URL appears to be correct.
Prior to this I have succeeded in uploading this video using the C# API so I know the video file is valid.
--Update
This is the apiURL value:
http://uploads.gdata.youtube.com/feeds/api/users/default/uploads
Make certain that videoFile actually points to the correct local file. The File(String) constructor won't verify that it actually exists. The MediaFileSource constructor and VideoEntry.setMediaSource() method also never check that the file is valid. The error message "Error writing request body to the server" sounds like the insert method can not find the body of the message it is trying to send.
File videoFile = new File("...");
if (videoFile.exists() == false) {
System.err.println("FAIL");
}
to test if the file exists.
If you are under a firewall env and had configured your proxy settings in jvm system properties. The try configuring your youtube service as:
service.setChunkedMediaUpload(MediaService.NO_CHUNKED_MEDIA_REQUEST);
or in your case
settings.setChunkedMediaUpload(MediaService.NO_CHUNKED_MEDIA_REQUEST);
since as you say is your YouTubeService instance.
hope this helps.

Categories