I am currently writing a web service that stores an image on a directory on my glassfish server instance. For some reason, when the web service is consumed from the client, it says that directory or the file is not found. I am passing a byte array to the method. Below is my code:
#WebMethod(operationName="upload")
public String upload(String fileName, byte[] imageBytes){
String filePath = "/bucketlister/images/feature pictures/"+fileName;
try{
FileOutputStream fos = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(imageBytes);
bos.close();
return "Received file:" + filePath;
}catch(IOException e){
throw new WebServiceException(e);
}
}
the FileOutputStream throws a FileNotFoundException. Any ideas? I would prefer to use a byte array, but I am open to other suggestions.
I guess the answer was staring at me all the while.. The filePath was pointing to only half the directory. It should have gone
String filePath ="home/user/glassfish4/domains/domain1/bucketlister/images/feature_picture/" + fileName;
I don't know if it changes anything, but I changed the "feature picture" directory to "feature_picture"
Related
I have create Rest Service and I am trying to Generate Zip file. This Zip file created from muliple PDF files which are downloaded using method InputStream inpuStream = new URL(url).openStream() . I am able to Generate Zip file Which included PDF files but PDF files are broken.
Even If i try to Generate it from String its coming as broken PDF and i am getting Error message "Not a supported File Type or file is broken or damaged". Its simple code but seems like i am unable to track the mistake.
I have provided my controller , service method for your reference.
1)Controller:
#GetMapping("/getZipFile")
public void getZipFile(HttpServletResponse response) throws RestException {
try {
ByteArrayOutputStream baos = generateZipService.getZipFile();
ServletOutputStream responseOutPutStream = response.getOutputStream();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=\"GeneratedZipFile.zip\"");
responseOutPutStream.write(baos.toByteArray());
responseOutPutStream.flush();
} catch (Exception e) {
throw new RestException("Error In downloading Zip File");
}
}
2)Service Method
public ByteArrayOutputStream getZipFile() throws Exception{
List<ZipFileName> zipFileNames= zipFileNameDao.getZipFileName();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut= new ZipOutputStream(baos);
for (String fileName : zipFileNames) {
InputStream inpuStream = new ByteArrayInputStream( "this is test to generarte pdf test file this is test tdfsfs this is test to generarte pdf test file this is test tdfsfs".getBytes(Charsets.UTF_8) );
createZipFile(inpuStream,zipOut,fileName);
inpuStream.close();
}
zipOut.flush();
baos.flush();
zipOut.close();
baos.close();
return baos;
}
3)createzipfile from service method :
```private void createZipFile(InputStream inputStream, ZipOutputStream zipOut,String fileName) throws IOException {
ZipEntry zipEntry = new ZipEntry(fileName+".pdf");
BufferedInputStream bis = new BufferedInputStream(inputStream);
zipOut.putNextEntry(zipEntry);
zipOut.write(IOUtils.toByteArray(inputStream));
zipOut.closeEntry();
bis.close();
inputStream.close();
}
Also , Another question is about using channels. I read channels are better when you have large files to downlaod from server . I have less then 20 kb of file so should I use Java.nio or just Zipoutputstream is fine.
I try with "response.setContentType("APPLICATION/ZIP")" but it didnt change the outcome of the project.
Thank you for your help..
The code worked fine only thing missing was to pass authentication with the openStream() method because of which I was getting the broken PDF. I opened the pdf with notepad++ and found the error ..
I resolved it.
Thank you
I have a question regarding dynamically creating and streaming ZIP files. I have multiple large files stored on remote HTTP servers (for example Amazon S3).
Now I want the user to download let's say 100 files as one ZIP file.
I could download all 100 files, zip them and stream them to the user, but that would be wasting lots of resources. So my approach is download the first file, stream it to the user, download the next file, stream it to the user and so on.
This is the test code:
public class TestController extends Controller {
public Result test() throws Exception {
InputStream is = getDynamicStreamSomewhere();
response().setContentType("application/zip");
response().setHeader("Content-Disposition", "attachment;filename=test.zip");
return ok(is);
}
private InputStream getDynamicStreamSomewhere() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
String url1 = "http://www.example.com/largefile1.bin";
String url2 = "http://www.example.com/largefile2.bin";
ZipEntry entry1 = new ZipEntry("file1.bin");
zos.putNextEntry(entry1);
URL website = new URL(url2);
InputStream in = website.openStream();
IOUtils.copy(in, zos);
in.close();
zos.closeEntry();
ZipEntry entr2 = new ZipEntry("file2.bin");
zos.putNextEntry(entr2);
URL websitea = new URL(url1);
InputStream ina = websitea.openStream();
IOUtils.copy(ina, zos);
ina.close();
zos.closeEntry();
return new ByteArrayInputStream(baos.toByteArray());
}
}
But as far as I debugged it, that does not really stream file by file but download everything and then stream it to the user.
What I am missing is something like flushing the output buffer to the user after every file (or maybe after each 4KB block).
I know how to do it with Java servlets, but not with Play Framework. Any help is appreciated!
Thank you!
For a class, I have to send a file of any type from my client to a server. I have to handle each packet individually and use UDP. I have managed to transfer the file from the client to the server, and I now have a file object which I cannot figure out how to save to a user specified directory.
f = new File(path + '\\' + filename);//path and filename are user specified.
FileOutputStream foutput = new FileOutputStream(f);
ObjectOutputStream output = new ObjectOutputStream(foutput);
output.writeObject(result);//result is a File
output.flush();
output.close();
Any time I run this code, it writes a new file with the appropriate name, but the text file I am testing ends up just containing gibberish. Is there any way to convert the File object to a file in the appropriate directory?
EDIT: As it turns out, I was misunderstanding what, exactly, a file is. I have not been transferring the data, but rather the path. How do I transfer an actual file?
ObjectOutputStream is a class that outputs a specific format of data to a text file. Only ObjectInputStream's readObject() can decoding that text file.
If you open the text file , it is just gibberish ,as you have seen.
you want this:
FileOutputStream fos = new FileOutputStream(path + '\\' + filename);
FileInputStream fis = new FileInputStream(result);
byte[] buf = new byte[1024];
int hasRead = 0;
while((hasRead = fis.read(buf)) > 0){
fos.write(buf, 0, hasRead);
}
fis.close();
fos.close();
If I understand your question, how about using a FileWriter?
File result = new File("result.txt");
result.createNewFile();
FileWriter writer = new FileWriter(result);
writer.write("Hello user3821496\n"); //just an example how you can write a String to it
writer.flush();
writer.close();
I'm not sure if this question has been asked before, but I could not find any resources on the internet answering my specific problem.
I am trying to upload a file from an Android app to my Openshift server/gear, where it will be stored. However, the issue I am facing is that whilst the file is being created at the Openshift side (I have checked using FTP), no data is being written to it.
The code snippet from the servlet that writes the data to the file is here:
int BUFFER_LENGTH = 4096;
DataInputStream din = new DataInputStream(req.getInputStream());
String fileName = din.readUTF();
String path = System.getenv("OPENSHIFT_DATA_DIR") + "/uploads/" + fileName + ".txt";
File f = new File(path);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[BUFFER_LENGTH];
int length = 0;
while ((length = din.read(buffer, 0, BUFFER_LENGTH)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
din.close();
It all seems to be correct, to me at least, and it worked when I tested it on a local tomcat server. For some reason, however, it doesn't work with Openshift, so there must be something I am missing.
Luckily there is a help center article for just this issue:
https://forums.openshift.com/how-to-upload-and-serve-files-using-java-servlets-on-openshift
It details the code for both uploading, and serving files on OpenShift via a Java Servlet, using the openshift data directory
It's time to change the downloaded file name in the Google Cloud Storage using java(BlobstoreService). Is there any provision in the BlobstoreService to change the file name before downloading that file? Is there any useful API for changing the filename? Here the thing that happens is, when I save a file in the GCS, it will generate a blob key. And the file type also changes in the Google cloud storage. Now I just want to change the file name before it downloads, and also the type of the file.
You can rename a file by reading the file in and saving it with the new name. Here is some sample code to get you started, you will likely need to add your own delete function in order to delete the old file:
public void moveFile(String fileName, String bucket, String newFilename, String contentType) throws IOException {
byte[] bytes = loadFile(bucket, fileName);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
saveToGcs(bucket, fileName, in, contentType);
}
public byte[] loadFile(String bucket, String fileName) throws IOException {
GcsFilename gcsFileName = new GcsFilename(bucket, fileName);
GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0);
InputStream in = Channels.newInputStream(readChannel);
return IOUtils.toByteArray(in);
}
private void saveToGcs(String bucket, String filename, InputStream inputStream, String mimeType) throws IOException {
GcsFilename gcsFilename = new GcsFilename(bucket, filename);
GcsFileOptions options = new GcsFileOptions.Builder().mimeType(mimeType).acl("public-read").build();
GcsOutputChannel writeChannel = gcsService.createOrReplace(gcsFilename, options);
BufferedOutputStream outputStream = new BufferedOutputStream(Channels.newOutputStream(writeChannel));
IOUtils.copy(inputStream, outputStream);
outputStream.close();
writeChannel.close();
}
Read here : https://cloud.google.com/storage/docs/copying-renaming-moving-objects#storage-rename-object-java
Create a copyWriter and copy the original blob to the renamed (new) address. Then delete the original