How to write java code for egnyte chunked upload and send to rest service of egnyte api.
https://developers.egnyte.com/docs/read/File_System_Management_API_Documentation#Chunked-Upload
long size = f.getTotalSpace();
int sizeOfFiles = 1024 * 1024;// 1MB
byte[] buffer = new byte[sizeOfFiles];
ResponseEntity<String> responseEntity = null;
String fileName = f.getName();
String url = DOWNLOAD_OR_UPLOAD + "-chunked" + egnyteSourcePath + f.getName();
HttpHeaders headers = buildEgnyteEntity();
HttpEntity entity = new HttpEntity<>(headers);
//try-with-resources to ensure closing stream
try (FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis)) {
int bytesAmount = 0;
while ((bytesAmount = bis.read(buffer)) > 0) {
//write each chunk of data into separate file with different number in name
String filePartName = String.format("%s.%03d", fileName, partCounter++);
File newFile = new File(f.getParent(), filePartName);
responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
}
}
return responseEntity;
I think there's a couple of things missing in your code.
First thing is that you don't specify required headers. You should provide X-Egnyte-Chunk-Num with int value with number of your chunk, starting from 1. In X-Egnyte-Chunk-Sha512-Checksum header you should provide SHA512 checksum.
Second thing is that first request will give you an UploadId in response header in X-Egnyte-Upload-Id. You need to specify that as a header in your second and following requests.
Third thing is that I don't see you use your bytesAmount in the request. I'm not sure you're providing the data.
I'm not a Java guy, more of a C# one, but I've written a post how to upload and download big files with Egnyte API on my blog: http://www.michalbialecki.com/2018/02/11/sending-receiving-big-files-using-egnyte-api-nuget-package/. This can give you an idea how sending loop can be structured.
Hope that helps.
Related
I am having trouble passing multiple parameters to GET resource in my controller. I have created a named query in my repository. When i call this GET endpoint, it should execute the named query by passing parameters.
Below code should take multiple parameters as input for example ID = 1,2,3,4 etc. It only takes single input as param.
#GetMapping("/message/{Ids}")
#CrossOrigin(origins = "*")
public void multidownload(#PathVariable Long[] Ids , HttpServletResponse response)throws Exception {
List<MessageRepository> messageRepository = Repository.findbyId(Ids);
String xml = new ObjectMapper().writeValueAsString(messageRepository);
String fileName = "message.zip";
String xml_name = "message.xml";
byte[] data = xml.getBytes();
byte[] bytes;
try (ByteOutputStream bout = new ByteOutputStream();
ZipOutputStream zout = new ZipOutputStream(bout)) {
zout.setLevel(1);
ZipEntry ze = new ZipEntry(xml_name);
ze.setSize(data.length);
zout.putNextEntry(ze);
zout.write(data);
zout.closeEntry();
bytes = bout.getBytes();
}
response.setContentType("application/zip");
response.setContentLength(bytes.length);
response.setHeader("Content-Disposition", "attachment; " + String.format("filename=" + fileName));
ServletOutputStream outputStream = response.getOutputStream();
FileCopyUtils.copy(bytes, outputStream);
outputStream.close();
}
downloaded zip file should contain multiple ID records which were passed as parameter when calling the GET endpoint.
can someone look into my code and point out what needs changing?
You can rewrite it to List of Ids - `List Ids
#GetMapping("/message/{Ids}")
#CrossOrigin(origins = "*")
public void multidownload(#PathVariable List<Long> Ids , HttpServletResponse response)throws Exception {
...
You achieve the multiple input parameters in POST request method.
In the request payload, please add this array of integer in your Request payload.
[1,2,3,4,5]
To achieve same thing in GET request method convert your array of integer into string.
Example:
localhost:8080/user/str=1,2,3
I have different types of files stored and I have a controller to download the files. The files are stored in base64 and I'm trying to download the file and the file seems to be corrupted althought the download works. I could really use some pointers to fix my problem.
Here is what I have so far.
#GetMapping("/attachments")
public ResponseEntity<InputStreamResource> getAttachment() {
String file = "iVBORw0KGgoAAAANSUhEUgAAALoAAAAyCAYAAADr7cFEAAAgAElEQVR4nO2df3idVZXvP99MzGTOye1Ne1NuH26pEJgKiLXlxJogKhRFYBwFfyDiNMjAiUKioMg4yFAeisAwWLxqU0qODJAq6r0KyI+K6FRBxxbmHIhMp3QQIpdCp1Ny29w+nPN0Mpl87x/vz3NykqYV7p3Rrj7pec/77nfttddee+211l57HzgIB+F3APRaIj+is3epxBXAO4BGoIh90/CmNQ+9lvUehINQC6+ZoLd39p4NvhPUXFWTmUB8HvjS8Mb+qncGh17+c1vrz1vS9tRrRddB+N2EhtcCaXtX7zzjWwzNJvzn8A832L4BWDT5Te2S2Ds4NNL4WtB1EH534TUR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Tr65P8CEtHnF7Z82nMAAAAASUVORK5CYIIA";
String decoded = new String(Base64.decodeBase64(file.getBytes()));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Encoding", "UTF-8");
headers.add(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=" + fileName);
InputStream targetStream = IOUtils.toInputStream(decoded, "UTF-8");
return ResponseEntity.ok().headers(headers).contentLength(decoded.length())
.contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(targetStream));
}
The base 64 encoded file is a PNG file. PNG files are binary files and cannot be represented as string and are not UTF-8 encoded. Just return the byte array.
#GetMapping("/attachments")
public ResponseEntity<byte[]> getAttachment() {
String file = "iVBORw0KG ... 5CYIIA";
byte[] decoded = Base64.getDecoder().decode(file);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
.filename(fileName).build();
headers.setContentDisposition(contentDisposition);
return ResponseEntity.ok().headers(headers)
.contentLength(decoded.length)
.body(decoded);
}
I'm working with an ionic application(like hybrid) which can play some videos.I want to add some headers to the request so that I override the "shouldInterceptRequest".
URL myUrl = new URL(real);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
for (Map.Entry < String, String > entry: headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
InputStream in = connection.getInputStream();
WebResourceResponse response = new WebResourceResponse("video/mp4", "UTF-8", in );
for (Map.Entry < String, List < String >> entry: connection.getHeaderFields().entrySet()) {
resHeaders.put(entry.getKey(), entry.getValue().get(0));
}
This code can't work.The video tag in html can't play the video.
So I add some code.
byte[] bytes = new byte[30 * 1024 * 1024];
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(bytes)) != -1) {
byteBuffer.write(bytes, 0, len);
}
bytes = byteBuffer.toByteArray();
WebResourceResponse response = new WebResourceResponse("video/mp4", "UTF-8", new ByteArrayInputStream(bytes));
When I read inputstream into bytes and send bytes to WebResourceResponse, the video can be play.However it means my application will use lots of memory if the video is large.
So that, I want to know is there any way to play the video without saving inputstream into bytes.
OK.Fianlly,I found my way.
Actually, my goal is to add custom headers to resource request and now I found there is an easier way to do it.
For example, if I want to load a image,I will use img tag like this,<img src="the_url_of_image">,and I can't add any header to the request unless I interecept the request.
However,we can use blob now.We can request the resource by using something like ajax and use createObjectURL to create a url links to the resource.
I'm retrieving a PDF file from a web server java, returning a byte array.
Need save the PDF on the local machine using C #, but the file is saved completely in blank, I think it is because of the byte array format is different.
Here is my code:
StreamReader responseReader = new StreamReader(webStream);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/pdf";
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
byte[] docByte = Encoding.ASCII.GetBytes(response);
File.WriteAllBytes(#"C:\file.pdf", docByte);
Any suggestions on how to save the PDF file normally?
Thank you for listening
// ...
Stream webStream = webResponse.GetResponseStream();
using (var stream = File.Create(#"C:\file.pdf"))
{
webStream.CopyTo(stream);
}
Why don't you do it simply with WebClient like this?
using System.Net;
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(URL, #"C:\file.pdf");
}
I use range hader, but not create correct file.
if I send Range bytes=0-8999 file weighs 9000 bytes and correct work.
if I send Range bytes=0-8999,9000-9999 file weighs 10213 bytes and NOT correct work.
File type mp3.
What could be wrong?
HttpGet first = new HttpGet("http://cs4832.vkontakte.ru/u50184979/audio/ef64581d913c.mp3");
first.addHeader("Accept-Ranges", "bytes");
first.addHeader("Range", "bytes=0-8999,9000-9999");
//first.addHeader("Accept-Ranges", "bytes");
HttpResponse response = httpclient.execute(first, localContext);
InputStream instream = response.getEntity().getContent();
File f = new File("outFile1.mp3");
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while ((len = instream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
instream.close();
See RFC 2616, Section 14.16:
When an HTTP message includes the content of multiple ranges (for example, a response to a request for multiple non-overlapping ranges), these are transmitted as a multipart message. The multipart media type used for this purpose is "multipart/byteranges" as defined in Appendix 19.2. See Appendix 19.6.3 for a compatibility issue.