I would like to upload a file from the web page using this strategy. i.e. Ajax file upload tutorial . It is going all fine, but the issue is on the server side, where I want to open this file and read its contents.
I am using the following signature for the method which is called on the submit of the form.
i.e.
public #ResponseBody String getFile(MultipartHttpServletRequest request)
Can any body please let me know that how can I extract the contents of the file?
MultipartHttpServletRequest extends MultipartRequest, which has methods for accessing the files.
You can do this:
MultipartFile file = request.getFile(paramName);
See http://docs.spring.io/spring-framework/docs/3.2.0.M1/api/org/springframework/web/multipart/MultipartRequest.html
Related
I am having HTML file which I want to send as a response for the rest call inside Apache camel RouteBuilder. The code looks like below
public class RestEndpointRouteBuilder extends RouteBuilder {
#Override
public void configure() {
rest("/form")
.post()
.produces(MediaType.TEXT_HTML_VALUE)
.to("file:target/classes/static/form.html");
}
But, I am getting below error when I call the API
org.apache.camel.component.file.GenericFileOperationFailedException: Cannot write null body to file: target\classes\static\form.html\ID-*****-***-****
at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:245)
at org.apache.camel.component.file.GenericFileProducer.writeFile(GenericFileProducer.java:277)
at org.apache.camel.component.file.GenericFileProducer.processExchange(GenericFileProducer.java:165)
at org.apache.camel.component.file.GenericFileProducer.process(GenericFileProducer.java:79)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
Basically, I want to return an HTML file, which is a ReactJS application, alongwith JS minified files. Could someone please help me with this?
There are several problems in your code:
The more appropriate HTTP method is rather GET instead of POST
The file component here is a to endpoint so it is used as a producer, in other words, it will save into the file instead of reading it as you expect.
The URI of the file component is incorrect, the URI format is file:directoryName[?options] which means that target/classes/static/form.html is supposed to be a directory, not a file.
What you try to achieve could be done as follow:
rest("/form")
// Fix #1: Use "get" instead of "post"
.get()
.produces(MediaType.TEXT_HTML)
.to("direct:fileContent");
from("direct:fileContent")
// Fix #2: Use "pollEnrich" to use the file component as a
// consumer to read the file
// Fix #3: Fix the URI to have the directory name on one side
// and the file name on the other side
.pollEnrich("file:target/classes/static?fileName=form.html");
NB: Even if what I described above will work, please note that a rest endpoint is not meant to be used for static content, you are supposed to use a reverse proxy instead.
I want to send across resource(say a image) from some URL to front-end.
The typical way of doing this is to create a File and build the response. Is there any way in which I don't have to create the File in java code and still send the resource to front-end.
Front-end cannot access the URL due to some constraints.
Currently the Pseudo code looks like this.
File file = new File(fullPath);
FileUtils.copyURLToFile(url, file);
ResponseBuilder response = Response.ok(modulePDF);
I want to send content of URL to front-end without creating file. Is there any way?
What way did have in mind to actually obtain the file without creating a File object?
Not sure I fully understand the complete requirement, but you don't have to create a File object. You can send out a byte[], or simply write it to the response output stream by returning StreamingOutput.
#GET
public StreamingOutput getString() {
return new StreamingOutput(){
#Override
public void write(OutputStream out)
throws IOException, WebApplicationException {
// write to the `out` stream
}
};
}
For anything more than that, you will have to greatly elaborate on your requirement. The information you've provided, (especially the highlighted line) doesn't quite paint a clear enough problem as to what actual problem is you are facing.
I'm doing a file upload, and I want to get the Mime type from the uploaded file.
I was trying to use the request.getContentType(), but when I call:
String contentType = req.getContentType();
It will return:
multipart/form-data; boundary=---------------------------310662768914663
How can I get the correct value?
Thanks in advance
It sounds like as if you're homegrowing a multipart/form-data parser. I wouldn't recommend to do that. Rather use a decent one like Apache Commons FileUpload. For uploaded files, it offers a FileItem#getContentType() to extract the client-specified content type, if any.
String contentType = item.getContentType();
If it returns null (just because the client didn't specify it), then you can take benefit of ServletContext#getMimeType() based on the file name.
String filename = FilenameUtils.getName(item.getName());
String contentType = getServletContext().getMimeType(filename);
This will be resolved based on <mime-mapping> entries in servletcontainer's default web.xml (in case of for example Tomcat, it's present in /conf/web.xml) and also on the web.xml of your webapp, if any, which can expand/override the servletcontainer's default mappings.
You however need to keep in mind that the value of the multipart content type is fully controlled by the client and also that the client-provided file extension does not necessarily need to represent the actual file content. For instance, the client could just edit the file extension. Be careful when using this information in business logic.
Related:
How to upload files in JSP/Servlet?
How to check whether an uploaded file is an image?
just use:
public String ServletContext.getMimeType(String file)
You could use MimetypesFileTypeMap
String contentType = new MimetypesFileTypeMap().getContentType(fileName)); // gets mime type
However, you would encounter the overhead of editing the mime.types file, if the file type is not already listed. (Sorry, I take that back, as you could add instances to the map programmatically and that would be the first place that it checks)
Hello I'm building a web application (online store) where an admin can upload a new product.
One of the input type is a file (image of the product)
I want the images of the products to be stored in a folder, and each product will have an image associated in the database table.
My question is, how does input type=file work? I still don't understand how when I submit the form a servlet will paste the image in the webpage folder, and how is the value (name of the image) going to be obtained to be stored in the database table?
For the other inputs i use "value" to get the info.
Thanks!
In java, its hard to do handle file uploads. But there are many libraries that do it. The most popular one is apache commons file uploads Here is an example on how to do that in java:
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
There are many more options that you should play around with.
how does input type=file work?
This is to be used in a <form> with multipart/form-data encoding. Once a file is selected and the form is submitted, then the file contents becomes part of the HTTP request body. In the servlet, it's available as "raw" data by request.getInputStream(). In servletcontainers supporting only servlet 2.5 or older, there was no API-provided facility to parse the data. Apache Commons FileUpload is the de facto standard. Since servlet 3.0 you can use the API-provided request.getParts() for this -which is under the covers using a licensed copy of Commons FileUpload.
See also:
How to upload files in JSP/Servlet?
How to retrieve uploaded file in JSP/Servlet?
I still don't understand how when I submit the form a servlet will paste the image in the webpage folder and how is the value (name of the image) going to be obtained to be stored in the database table?
You should not only be interested in the file name. You should also be interested in the file contents. Whatever way you choose to parse the uploaded file out of the request body, you should end up with the file contents in flavor of an InputStream or a byte[]. You can write it to local disk file system using FileOutputStream and store the unique filename in the DB the usual JDBC way.
See also:
How to get full file path of uploaded file in Firefox? - to clear out a major misunderstanding
When a file is uploaded to a web server, the following information is usually included (or similar):
Content-Disposition: form-data; name="fileInput"; filename="myFile.txt"
Content-Type: application/octet-stream
The filename contains either the name of the file or the full path depending on the browser.
If you use a program like Fiddler, you can see exactly what's going on when you upload a file.
In jsp/java how can you call a page that outputs a xml file as a result and save its result (xml type) into a xml file on server. Both files (the file that produces the xml and the file that we want to save/overwrite) live on the same server.
Basically I want to update my test.xml every now and then by calling generate.jsp that outputs a xml type result.
Thank you.
If the request is idempotent, then just use java.net.URL to get an InputStream of the JSP output. E.g.
InputStream input = new URL("http://example.com/context/page.jsp").openStream();
If the request is not idempotent, then you need to replace the PrintWriter of the response with a custom implementation which copies the output into some buffer/builder. I've posted a code example here before: Capture generated dynamic content at server side
Once having the output, just write it to disk the usual java.io way, assuming that JSP's are already in XHTML format.
Register a filter that adds a wrapper to your response. That is, it returns to the chain a new HttpServletResponse objects, extending the original HttpServletResponse, and returning your custom OutputStream and PrintWriter instead of the original ones.
Your OutputStream and PrintWriter calls the original OutputStream and PrintWriter, but also write to a your file (using a new FileOutputStream)
Why don't you use a real template engine like FreeMarker? That would be easier.