I have a rest api to download a file from server ,
#Path("/file")
public class FileService {
#GET
#Path("/get")
#Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response getFile(String filePath) {
File file = new File(filePath);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=\"file_from_server.log\"");
return response.build();
}
}
How to receive the file object from the javax.ws.rs.core.Response and write the content of the file in local without using browser.
I am tried below ,
InputStream in = response.readEntity(InputStream.class);
But it is not working.
Related
Greetings to the community! I am currently developing a RESTful web service in Java using the JAX-rs library. What I would like to do is make clients able to upload a file via the service. I successfully managed to achieve this using the following piece of code
#Consumes({"application/json"})
#Produces({"application/json"})
#Path("uploadfileservice")
public interface UploadFileService {
#Path("/fileupload")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
Response uploadFile(#FormDataParam("file") InputStream uploadedInputStream)
}
Implementation class
#Service
public class UploadFileServiceImpl implements UploadFileService {
#Override
public Response uploadFile(InputStream uploadedInputStream){
String fileToWrite = "//path/file.txt" //assuming a upload a txt file
writeToFile(uploadedInputStream, fileToWrite); //write the file
}
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am using POSTMAN as a client to test my web service and I am facing the following problem: When I upload a .txt file, that files gets appended with some other details of the file
Example:
File sent
Postman Request
File stored on my filesystem
Any idea why this happens? Maybe I am missing something in the Headers section of my request? Or maybe any issue is caused because of the MediaType I am consuming in my web service endpoint?
Thanks in advance for any help :)
PS
If I upload a .pdf file it is not leaded to corruption and the .pdf file is stored normally on my filesystem
Your method signature should be
Response uploadFile(#FormDataParam("file") FormDataBodyPart uploadedFile)
and you can get content of the file as
InputStream uploadedInputStream = uploadedFile.getValueAs(InputStream.class)
Hope this helps.
Finally I found a workaround for my problem using the Attachment class of org.apache.cxf:
#Consumes({"application/json"})
#Produces({"application/json"})
#Path("uploadfileservice")
public interface UploadFileService {
#Path("/fileupload")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
Response uploadFile(#Multipart("file") Attachment attr)
}
#Service
public class UploadFileServiceImpl implements UploadFileService {
#Override
public Response uploadFile(Attachment attr){
String pathToUpload= "//path//.txt"
try{
attr.transferTo(new File(pathToUpload)); //will copy the uploaded file in
//this destination
}
catch(Exception e){
}
}
Hi I have a requirement to download a pdf file after method execution.
i write code like below
private static final String FILE_PATH = "d:\\Test2.zip";
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=newfile.zip");
return response.build();
}
But as I have to send huge data in request I want to use #POST instead of #GET signature.How to do that please help
Hi I am returning a file by using the below code in REST Service Class
#Path("/file")
public class FileService {
private static final String FILE_PATH = "c:\\file.log";
#GET
#Path("/get")
#Produces("text/plain")
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=\"file_from_server.log\"");
return response.build();
}
}
I just want to know How I can pass a file which comes from a HTTP call for e.g
"http://www.analysis.im/uploads/seminar/pdf-sample.pdf".The above code calls from a drive .I want to return files from a server through REST call.
You have to read the file content, set the appropriate media type and return the content as byte array similar to the following:
final byte[] bytes = ...;
final String mimeType = ...;
Response.status(Response.Status.OK).entity(bytes).type(mimeType).build();
I want send my android .apk file to my client(browser) from java restful web service.I try to use bellow code. But it produce a file named "MyPath" without any file extension (require .apk).Thanks in advance
#Path("MyPath")
public class MyPathResource {
#Context
private UriInfo context;
/**
* Creates a new instance of MyPathResource
*/
public MyPathResource() {
}
#GET
#Produces("application/vnd.android.package-archive")
public File getFile() {
// return my file
return new File("E:\\CommandLineAndroidProjet1\\bin\\FirstCommandLineApp-release.apk");
}
}
Try creating an explicit javax.ws.core.Response:
return Response.status(Response.Status.OK)
.entity(entity)
.header("Content-Disposition", "attachment; filename=" + fileName)
.build();
while entity is your file as byte array and fileName is the file name with .apk suffix.
I want to return a zipped file from my server-side java using JAX-RS to the client.
I tried the following code,
#GET
public Response get() throws Exception {
final String filePath = "C:/MyFolder/My_File.zip";
final File file = new File(filePath);
final ZipOutputStream zop = new ZipOutputStream(new FileOutputStream(file);
ResponseBuilder response = Response.ok(zop);
response.header("Content-Type", "application/zip");
response.header("Content-Disposition", "inline; filename=" + file.getName());
return response.build();
}
But i'm getting exception as below,
SEVERE: A message body writer for Java class java.util.zip.ZipOutputStream, and Java type class java.util.zip.ZipOutputStream, and MIME media type application/zip was not found
SEVERE: The registered message body writers compatible with the MIME media type are:
*/* ->
com.sun.jersey.core.impl.provider.entity.FormProvider
What is wrong and how can I fix this?
You are delegating in Jersey the knowledge of how to serialize the ZipOutputStream. So, with your code you need to implement a custom MessageBodyWriter for ZipOutputStream. Instead, the most reasonable option might be to return the byte array as the entity.
Your code looks like:
#GET
public Response get() throws Exception {
final File file = new File(filePath);
return Response
.ok(FileUtils.readFileToByteArray(file))
.type("application/zip")
.header("Content-Disposition", "attachment; filename=\"filename.zip\"")
.build();
}
In this example I use FileUtils from Apache Commons IO to convert File to byte[], but you can use another implementation.
You can write the attachment data to StreamingOutput class, which Jersey will read from.
#Path("/report")
#GET
#Produces(MediaType.TEXT_PLAIN)
public Response generateReport() {
String data = "file contents"; // data can be obtained from an input stream too.
StreamingOutput streamingOutput = outputStream -> {
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(outputStream));
ZipEntry zipEntry = new ZipEntry(reportData.getFileName());
zipOut.putNextEntry(zipEntry);
zipOut.write(data); // you can set the data from another input stream
zipOut.closeEntry();
zipOut.close();
outputStream.flush();
outputStream.close();
};
return Response.ok(streamingOutput)
.type(MediaType.TEXT_PLAIN)
.header("Content-Disposition","attachment; filename=\"file.zip\"")
.build();
}
In Jersey 2.16 file download is very easy
Below is the example for the ZIP file
#GET
#Path("zipFile")
#Produces("application/zip")
public Response getFile() {
File f = new File(ZIP_FILE_PATH);
if (!f.exists()) {
throw new WebApplicationException(404);
}
return Response.ok(f)
.header("Content-Disposition",
"attachment; filename=server.zip").build();
}
I'm not sure I it's possible in Jersey to just return a stream as result of annotated method. I suppose that rather stream should be opened and content of the file written to the stream. Have a look at this blog post. I guess You should implement something similar.