I want to write an excel and send it to the user as a response in an application using Play framework 1.x. But I am not sure how to set the response content-type/MIME-type for returning doc or excel file.
Let me know the steps for this.
From the documentation:
To serve binary data, such as a file stored on the server, use the renderBinary method. For example, if you have a User model with a play.db.jpa.Blob photo property, add a controller method to load the model object and render the image with the stored MIME type:
public static void userPhoto(long id) {
final User user = User.findById(id);
response.setContentTypeIfNotSet(user.photo.type());
java.io.InputStream binaryData = user.photo.get();
renderBinary(binaryData);
}
Related
I am currently writing a backend which takes in one or many image/video-files to be uploaded into Azure Blob Storage. I am however struggling to set the Content-Type of the files. The Content-Type is by default set to be "application/octet-stream", but I want to dynamically set them by using the file.getContentType() method.
The code looks like this:
public void uploadToContainer(BlobClient blobClient, MultipartFile file) {
try {
blobClient.upload(file.getInputStream(), file.getSize());
} catch (Exception e) {
//TODO:
// Better error handling
e.printStackTrace();
}
}
Does anyone know how I can accomplish this?
Faced the same issue uploading JSON file, came up with this from stepping through the
blobClient.upload method you're current using:
BlobHttpHeaders jsonHeaders = new BlobHttpHeaders()
.setContentType(MediaType.APPLICATION_JSON_VALUE);
BinaryData data = BinaryData.fromStream(file.getInputStream(), file.getSize());
BlobParallelUploadOptions options = new BlobParallelUploadOptions(data)
.setRequestConditions(new BlobRequestConditions()).setHeaders(jsonHeaders);
blobClient.uploadWithResponse(options, null, Context.NONE);
Note this is using azure-storage-blob v12.19.0
To set content type of a blob at the time of uploading, you will need to use the following method: uploadWithResponse(InputStream data, long length, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String,String> metadata, AccessTier tier, BlobRequestConditions requestConditions, Duration timeout, Context context) instead of upload method that you're using currently.
You will be able to define content type using BlobHttpHeaders.
How to upload an image and saved into the database and that image should be shown on the user profile page? The image can be of any type jpg, jpeg and png. I am using JSP, jQuery and Spring MVC framework and Java and Spring data jpa.
I am not using servlet in my application. I am new to this field and not able to complete it.
You need a VARBINARY column to contain the image. Open the file using an InputStream, load byte[]s from it, and write that into the column.
You need another column to save the mime file type. You can obtain the file type with java.nio.file.Files.probeContentType( Path path )
In your response headers, you need to:
Use setContentLength() to set the length of the file.
Use setContentType() to set the mime image type.
If your database offers a means to create an InputStream on a varbinary column, use it. Otherwise, you need to read the contents of your varbinary column into a byte[], and then create a ByteArrayInputStream on the byte[].
Finally, you need to construct a response entity using the constructor that accepts an input stream: return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);
My requirement is to upload a JPEG/PDF file & save it as BLOB.
We have done it. But if server side error occurs which redirects to JSP page, I will get all data (e.g. input fields, drop downs, checkbox, etc.) except file.
Then again I need to choose a file.
Is there any way to preserve a file or send a file from controller to JSP.
No it is not possible.
The simplest workaround is to keep the uploaded file in session so that you can recover it during the next form submission. Take care to users working with several tabs/windows: use a session key that clearly identifies the form on which the user is working. You could for example generate a unique identifier that you then store in a hidden field of the form.
To be able to download it again, you would need to provide second mapping that retrieves the file from the session.
MultipartFile inputFile = fileUploadBean.getFile();
HttpSession session = request.getSession();
if(!(inputFile.isEmpty())) {
session.setAttribute("inputFile", inputFile);
}
logger.info("inputFile : " + session.getAttribute("inputFile"));
if(inputFile.isEmpty() && session.getAttribute("inputFile")!=null) {
inputFile = (MultipartFile)session.getAttribute("inputFile");
}
This is what I did.
I have a Struts2 jsp page their i am sending one image, Temporary file path is comming to my java class after form submission but i do not know how can to save that path in db by changing it to Blob type.. Please consider this image columns is of blob type in my database table..
Here is the output what am getting in my Javaclass after the form submission:
My image path:
F:\Documents and Settings\software.netbeans\7.0\apache-tomcat-7.0.11_base\work\Catalina\localhost\AIGSA\upload__214d4f3e_136e8b74d9c__7fff_00000021.tmp 105542
filenames:
* Winter.jpg
Code:
for (File u: repImage)
{
System.out.println("*** "+u+"\t"+u.length());
}
int saveToDb= mo.addMembers(memberName, repImage);
How can I send my form Image to this {repImage Name, so that it will be easy to save it so my db
am not sure, but try:
int saveToDb= mo.addMembers( memberName, repImage.getBytes() );
If I understand your question properly, you want to store the binary data in your database. I'd say this is a bad idea in the first place for multiple reasons. A better method would be to reference a relative path that you can then use in your web application or the file system directly. Better yet, just store the reference to the location in Amazon/S3 where you want to save it/use it.
Regardless, to answer your question you would want to use ByteArrayOutputStream.
I have a web application that can display a generated PDF file to the user using the following Java code on the server:
#Path("MyDocument.pdf/")
#GET
#Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
PdfGenerator generator = new PdfGenerator(getEntity());
generator.generatePDF(output);
} catch (Exception e) {
logger.error("Error getting PDF file.", e);
throw new WebApplicationException(e);
}
}
};
}
This code takes advantage of the fact that I only need so much data from the front end in order to generate the PDF, so it can easily be done using a GET function.
However, I now want to return a PDF in a more dynamic way, and need a bunch more information from the front end in order to generate the PDF. In other areas, I'm sending similar amounts of data and persisting it to the data store using a PUT and #FormParams, such as:
#PUT
#Consumes({"application/x-www-form-urlencoded"})
public void put(#FormParam("name") String name,
#FormParam("details") String details,
#FormParam("moreDetails") String moreDetails...
So, because of the amount of data I need to pass from the front end, I can't use a GET function with just query parameters.
I'm using Dojo on the front-end, and all of the dojo interactions really don't know what to do with a PDF returned from a PUT operation.
I'd like to not have to do this in two steps (persist the data sent in the put, and then request the PDF) simply because the PDF is more "transient" in this uses case, and I don't want the data taking up space in my data store.
Is there a way to do this, or am I thinking about things all wrong?
Thanks.
I can't quite understand what do you need to accomplish - looks like you want to submit some data to persist it and then return pdf as a result? This should be straightforward, doesn't need to be 2 steps, just submit, on the submit save the data and return PDF.
Is this your problem? Can you clarify?
P.S.
Ok, you need to do the following in your servlet:
response.setHeader("Content-disposition",
"attachment; filename=" +
"Example.pdf" );
response.setContentType( "application/pdf" );
Set the "content-length" on the response, otherwise the Acrobat Reader plugin may not work properly, ex. response.setContentLength(bos.size());
If you provide output in JSP you can do this:
<%# page contentType="application/pdf" %>