This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
How can I upload files and get other paramaters of a form? I want to handle multi part requests in Java servlet.
To browse and select a file for upload you need a <input type="file"> field in the form. As stated in the HTML specification you need to use the POST method and the enctype attribute of the form has to be set to multipart/form-data.
<form action="uploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
After submitting such a form the form data is available in multipart format in the HttpServletRequest#getInputStream(). For testing(!) purposes you can read the stream using the following snippet:
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
You however need to parse the stream byte by byte (instead of char by char). Prior to the fresh new Servlet 3.0 API, the standard Servlet API didn't provide any builtin facilities to parse them. The normal form fields are also not available the usual request.getParameter() way, they are included in the multipart form data stream.
If you're not on Servlet 3.0 yet (which is only bit less than 2 monts old), then you need to parse the stream yourself. Parsing such a stream requires precise background knowledge of how multipart form data requests are specified and structured. To create a perfect multipart parser you'll have to write a lot of code. But fortunately there's the Apache Commons FileUpload which has proven its robustness with years. Carefully read both the User Guide and Frequently Asked Questions to find code examples and learn how to use it to an optimum degree (take MSIE into account!).
Step 1
Read adatapost's post.
Step 2
Check out the Apache Commons FileUpload project.
There's a similarly workable solution by O'Reily, but its license of use requires you buy a book, and even that requirement is so poorly articulated that I won't benefit it with yet another link.
Step-1
set enctype form tag attribute.
<form enctype="multipart/form-data" ....>
<input type="file" id="file1" name="file"/>
.... other stuff
</form>
Step-2
Read Justin's post.
To deal with enctype="multipart/form-data" we can not use request.getParameter() directly
Now to deal with the problem
Now, for uploading a file to the server, there can be various ways. But, I am going to use MultipartRequest class provided by oreilly. For using this class you must have cos.jar file.
public class UploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
MultipartRequest m=new MultipartRequest(request,"d:/new");
out.print("successfully uploaded");
}
}
this will upload your file to d:/new
Now to retrive parameter of multipart request
you have to use FilenameUtils class and getOriginalFileName() method of MultipartRequest class.
String file = FilenameUtils.getName(req.getOriginalFileName("myfile"))+"\\";
String message = req.getParameter("message");
This does not work for IE7 and below. Apparently you need to add another attribute to your form encoding ="multipart/form-data"
Related
How could I submit a multipart form using slim3 MVC framework for Google app Engine?
Example:
form.jsp:
<form enctype="multipart/form-data">
<input type=file name='filename'/>
<input type='text' name='title'/>
</form>
controller/action:
request.getParameter("title");
not working. It works only if enctype is not multipart.
What can I do?
I have tried to use
MultipartRequest req = new MultipartRequest(request, ".");
It just crashes.
When you use enctype="multipart/form-data", you obtain null values when you try to get data using getParameter, I don't remember the especific reason, but it works that way, so this is not a problem with your implementation.
One solution, using slim3, is to use getAttribute instead of getParameter. In this case, if you need to get more than one value associated whit one of your inputs, for example, if you are submitting a form and you have a group of checkboxes, you can add the word Array at the end of the name of the checkboxes in your form; this way, when you get the attribute, slim3 converts it automaticcally into an array of Strings.
You can check this information in the slim3 documentation.
I hope this helps,
Farewell.
Just like title, I want to ask, how to adding pdf files with upload form to my storage folder (e.g: uploadData) then its added to database as a file too in JSP.
If it not possible, it's ok to added to database as a text.
If it possible as a file, what type of my table for that pdf? blob? or text?
I accept blog links/other links that relevant for my problem
sorry for bad english.
Servlet 3.0 container's has standard support for multipart data. It also has the support to write to local file system. First you should be writing a HTML page which takes the file input along with other input parameters.
<form action="uploadservlet" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="text" name="age" />
<input type="file" name="photo" />
<input type="submit" />
</form>
Now write a UploadServlet which uses the Servlet 3.0 Upload API. Here is the code which demonstrates the usage of API. Fist the servlet handling multipart data should define MultiPartConfig using any of the two approaches:
#MultiPartConfig annotation on Servlet Class
In web.xml, by adding entry inside definition.
Here is the UploadServlet,
#MultipartConfig
public class UploadServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse responst) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
if (parts.size() != 3) {
//can write error page saying all details are not entered
}
Part filePart = httpServletRequest.getPart("photo");
InputStream imageInputStream = filePart.getInputStream();
//read imageInputStream
filePart.write("somefiepath");
//can also write the photo to local storage
//Read Name, String Type
Part namePart = request.getPart("name");
if(namePart.getSize() > 20){
//write name cannot exceed 20 chars
}
//use nameInputStream if required
InputStream nameInputStream = namePart.getInputStream();
//name , String type can also obtained using Request parameter
String nameParameter = request.getParameter("name");
//Similialrly can read age properties
Part agePart = request.getPart("age");
int ageParameter = Integer.parseInt(request.getParameter("age"));
}
}
If you are not using Sevlet 3.0 Container, you should be truing Apache Commons File Upload. Here are the links for using Apache Commons File Upload:
Using Apache Commons File Upload
Apache Commons File Upload Example
References:
File Upload Using Servlet 3.0
Servlet 3.0 javax.servlet.http.HttpServletRequest API
Servlet 3.0 javax.servlet.http.Part API
Uploading File using Servlet 3.0
The easiest way I know of to handle file uploads is by using Commons FileUpload. The documentation gives you a step by step overview of how to accept uploaded files, including how to easily copy them into a file.
Should you decide to put the PDF in a database (I wouldn't do that), BLOB is your best choice, a PDF file isn't text.
I would however advise not to cram all that logic in a JSP but in a servlet instead.
I've created a form and I need the user to enter some info then upload a picture.
So lets say I have something like this:
<form method="post" enctype="multipart/form-data" action="some servlet/filter">
<input type="file" name="logo">
</form>
I need to use java to change that data to a byte[] then to blob so I can insert to a table.
How do I get the data from this form?
A bit of info on this:
I created the page using javascript, then when submitted it will call a java function to handle the data from the form. It seems that when I submit the form the data for the file is not passed over to the servlet.
So far the few methods I've tried have returned null and I'm outta ideas...
Any examples/help is greatly appreciated!
I think the main question I have is where is the file data stored before the java file start working on it? Is a special global variable holding the data or something like that?
You can use the Apache Commons FileUpload library.
The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
FileUpload parses HTTP requests which conform to RFC 1867, "Form-based File Upload in HTML". That is, if an HTTP request is submitted using the POST method, and with a content type of "multipart/form-data", then FileUpload can parse that request, and make the results available in a manner easily used by the caller.
If I understood you right, you need something similar to this example:
http://www.servletworld.com/servlet-tutorials/servlet-file-upload-example.html
I used the following tutorial one year ago:
http://balusc.blogspot.com/2009/12/uploading-files-in-servlet-30.html
It looks like it's a lot, but it's actually easy to understand, and it has a lot of good information.
i written some code in JSP like this--
<input type="file" name="imagename" >
and in servlet i am retrieving 'imagename' value. But it is giving the name of the image instead of full path. My servlet code is like this:
String imagename = request.getParameter("imagename");
and i dont want to use javascript. any ideas? Thanks in advance
Maybe you should checkout this question: How to get the file path from HTML input form in Firefox 3
There is little to no reason why server should have to know full file path. If you want to upload a file, you'll need to use an appropriate library like Apache Commons FileUpload and transfer the file using.
<form action="upload-script-url" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
Apache Commons FileUpload will then accept and transform encoded file into a usable form.
Otherwise you'll need to use JavaScript to get that path.
Assuming that you are trying to upload a file to your server, please note that file uploads are a little more than what you are trying to do - do not expect that if you have a "file" input type in a form, on submission the file just reaches your sever, with no effort. There is a certain procedure to do that.
This article might e a good reference : http://www.cs.tut.fi/~jkorpela/forms/file.html
For Java, use Apache's commons-fileupload : http://commons.apache.org/fileupload/
imagename contains the variable you pass to the servlet... the actual HTTP request parameter. If you want the full path, be sure that the program that is calling your HTTP page is passing the full path instead of just the image name.
This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 6 years ago.
I am new to JSP and related technologies. I need to write a JSP form with some required fields (including Captcha), the form will require validation. Upon successful submission of the form, it should be able to email to a stated email address which is grabbed/parsed from a .txt file.
That is basically the flow. But technically how should I do it in JSP/java? Is there any good tutorial referencing to my above form requirement? How should I be able to grab/parse the text file. And lastly,
I remembered that php has a function called mail() to do the emailing, how should I do it in jsp?
Thank you very much.
JSP is just a view technology providing a template to write client side markup/style/scripting languages in, such as HTML/CSS/JS code, alongside with the possibility to control the page flow dynamically with help of taglibs such as JSTL and access to backend data with help of EL. In your speficic case a plain vanilla HTML form would already suffice.
<form action="servletname" method="post">
<input type="text" name="foo"><br>
<input type="text" name="bar"><br>
<input type="submit"><br>
</form>
To control, preprocess and/or postprocess the request and response, the best way is to use a Servlet. Basically just extend HttpServlet and implement the doGet() to preprocess data or the doPost() to postprocess the data. The servlet can be mapped on a certain url-pattern in web.xml. The HTML form action URL should match this url-pattern.
If you want to make use of the very same form to redisplay the submitted page and any error messages, then you can just make use of EL:
<form action="servletname" method="post">
<input type="text" name="foo" value="${param.foo}" ${not empty messages.succes ? 'disabled' : ''}>
<span class="error">${messages.foo}</span><br>
<input type="text" name="bar" value="${param.bar}" ${not empty messages.succes ? 'disabled' : ''}>
<span class="error">${messages.bar}</span><br>
<input type="submit">
<span class="succes">${messages.succes}</span><br>
</form>
Where ${messages} is basically a Map<String, String> which you've put in the request scope in the servlet. For example:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
if (foo == null || foo.trim().isEmpty()) {
messages.put("foo", "Please enter this field");
}
if (bar == null || bar.trim().isEmpty()) {
messages.put("bar", "Please enter this field");
}
if (messages.isEmpty()) {
YourMailer.send(createTemplate(foo, bar), mailto);
messages.put("succes", "Mail successfully sent!");
}
// At end, forward request to JSP page for display:
request.getRequestDispatcher("pagename.jsp").forward(request, response);
}
More about JSP/Servlet can be found in Java EE 5 tutorial part II chapters 4-9 and in Marty Hall's Coreservlets.com tutorials. To go a step further you can always abstract all the boilerplate stuff (request parameter retrieval, value conversion/validation, event handling, navigation, etcetera) away with help of any MVC framework which is built on top of Servlet API, like Sun JSF, Apache Struts, Spring MVC, etcetera.
With regard to captcha's, you can just use any Java Captcha API to your taste and follow the instructions. Often they have their own servlet/filter which stores a key/toggle/signal in the request or session scope which determines whether the captcha did match or not. You can just access its outcome inside your servlet.
With regard to mailing, you can just use any Java mail API to your taste, however the choice is only limited to the great JavaMail API and the more convenienced one provided by Apache which is built on top of JavaMail API.
That's a lot of questions in one question; here are a couple links which might be helpful (i.e., we've used them in the past):
Kaptcha: http://code.google.com/p/kaptcha/
JavaMail: http://java.sun.com/products/javamail/
Try using skeleton app AppFuse. It offers different frameworks from the basic to advanced ones. Here's an article on captcha integration.