Below I have a code that should accept a user's uploaded image in the form of an input element and push it to a MySQL Database. I am using Tomcat 9. Why is it not working yet no exceptions are being thrown? Nothing is being pushed to the database and there is no way of telling to what point the code is being executed. Note that I have embedded the class within the jsp file as IntelliJ has issues with separate servlet classes. Also note that the code was influenced by BalusC's answer. If possible, could anyone suggest an alternative code that can be used instead?
<form action="trial4.jsp" method="post" enctype="multipart/form-data">
<input type="text" name="description"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
static String URL = "localhost:3306/";
static String DATABASE_NAME = "MYDB";
static String USERNAME = "user";
static String PASSWORD = "";
#WebServlet("/upload")
#MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
// ... (do your job here)
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + URL + DATABASE_NAME, USERNAME, PASSWORD);
PreparedStatement ps = con.prepareStatement("insert into data(image) values(?)");
ps.setBinaryStream(1, fileContent);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
For other people who are facing a similar challenge, there is a repo that has really helped. The repo owner deserves a cup of coffee.
EDIT 03/2022
The documentation provides a good solution, one that is bettered by the fact that it does not involve third party libraries.
Related
I am using the example provided by #BalusC in the question. But I am getting an exception
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
org.apache.catalina.connector.Request.parseParts(Request.java:2824)
org.apache.catalina.connector.Request.getParts(Request.java:2792)
org.apache.catalina.connector.Request.getPart(Request.java:2961)
org.apache.catalina.connector.RequestFacade.getPart(RequestFacade.java:1105)
com.example.JSPtest.upload.doPost(upload.java:36)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:689)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
This is what I have done.
<form action="upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
static String URL = "localhost:3306/";
static String DATABASE_NAME = "DB";
static String USERNAME = "user";
static String PASSWORD = "";
#WebServlet("/upload")
#MultipartConfig(maxFileSize = 16*1024*1024)
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
// ... (do your job here)
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + URL + DATABASE_NAME, USERNAME, PASSWORD);
PreparedStatement ps = con.prepareStatement("insert into data(image) values(?)");
ps.setBinaryStream(1, fileContent);
int result = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The data column is a blob. Note I have not used servlets as IntelliJ has an issue where it is not finding the java servlet class files.Any help?
Add this to web.xml:
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.
Form
<div class="row">
<form method="POST" action="login">
<div class="form-group">
<label>Username</label>
<input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="pword" name="pword" placeholder="pword" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
</div>
Login Servlet Page
#WebServlet("/login")
public class login extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uname = request.getParameter("uname");
String pass = request.getParameter("pword");
if(uname.equals("John") && pass.equals("123"))
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
session.putValue("username", uname);
ServletContext context=getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("second");
rd.forward(request, response);
}
}
Second Servlet Page
#WebServlet("/second")
public class second extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String uname = (String)session.getValue("uname");
out.println("User Name is " + uname);
}
There are some big differences between redirect and forward . This article will help you to understand better your problem.
Some things to keep in mind from the article :
FORWARD
1) Request and response objects will remain the same object after forwarding. Request-scope objects will be still available (this is why if you try to add the "/" you get the 405 status - it will try to forward you to the "/second" servlet but the only request overridden is GET)
REDIRECT
1) The request is redirected to a different resource
2) A new request is created
So instead of using rd.forward I would suggest you to use the sendRedirect() method from HttpServletResponse class.
response.sendRedirect(request.getContextPath() + "/second");
AND the correct way to get the session username attribute is this:
String uname = (String) session.getValue("username");
Otherwise it will try to look after uname key which is not set. The uname was only a value mapped to the username key ( session.putValue("username",uname);
this exception indicates, path does not start with a "/".
try below instead.
RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");
This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 7 years ago.
Trying to upload a file to my servlet without page refresh with ajax.
Been stuck at this for some days now, and just can't let it go.
my form:
<form method="POST" id="changeImage2" enctype="multipart/form-data">
<input type="file" name="photo" /> <br>
<input type="button" value="Change Picture" id="changeImage1">
</form>
my servlet:
#MultipartConfig
public class changeImage extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Part filePart = req.getPart("photo");
Object email = req.getSession().getAttribute("email");
Object name = req.getSession().getAttribute("name");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection myConn = DriverManager.getConnection("", "", "");
PreparedStatement ps = myConn.prepareStatement("update user set profilePicture=? where email=? and name=?");
ps.setBlob(1, filePart.getInputStream());
ps.setString(2, (String) email);
ps.setString(3, (String) name);
ps.executeUpdate();
} catch (Exception e){
e.printStackTrace();
}
}
}
my ajax/jquery:
<script>
$(document).ready(function() {
$('#changeImage1').click(function() {
var dataForm = $('#changeImage2').serialize();
$.ajax({
type : 'POST',
url : 'changeImage',
data : dataForm,
success : function(data) {
$('#gg1').text(data);
},
error : function() {
$('#gg1').text("Fail");
},
});
});
});
</script>
When running this I get the error:
SEVERE: Servlet.service() for servlet [changeImage] in context with
path [/Event] threw exception
[org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException:
the request doesn't contain a multipart/form-data or
multipart/form-data stream, content type header is null] with root
cause
org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException:
the request doesn't contain a multipart/form-data or
multipart/form-data stream, content type header is null
I tried use another form and do without the ajax/jquery:
<form action="changeImage" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Change Picture" />
</form>
With this it works. So I'm guessing the JDBC and Servlet is sat up properly. And that I'm not using Ajax/Jquery properly.
In your code you write:
ps.setBlob(5, (Blob) InputStream);
According to javadoc for PreparedStatement this int, 5 is the parameter index. As the error is stating you only have 3 parameters.
You need to change this to 3? - looking at your SQL statement I think you may have forgotten you have copied and pasted from somewhere and haven't yet edited it.
These lines are the problem, you can't use Part object as Blob or InputStream. A cast exception should happen there.
Part filePart = req.getPart("photo");
Part InputStream = filePart; //this line is not needed at all
ps.setBlob(1, (Blob) InputStream);
Try something like this
ps.setBlob(1, filePart.getInputStream());
or
ps.setBinaryStream(1, filePart.getInputStream());
I have a java upload servlet and jsp form. the upload portion is working fine but i cannot get the regular form values in the upload servlet java code so that i can use these. Right now, I am trying to get the form data with request.getParameter("name"); but it is return null values. I am able to get the field values using item.getFieldName() and item.getFieldValue() but these are not really usable in additional processes in the item.iterator but these are not usable in further operations. For example, I want to pull in the email address field value so that I can send an email at the end of my upload servlet. I cannot use this data if I cannot make it into a string or variable which is where I am having issues. Any advice?
jsp file:
jsp form:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Username: <input type="text" name="username" value="username"/><br>
E-mail: <input type="email" name="email" autocomplete="on"><br>
<br>
Select file to upload:<input type="file" name="uploadFile" /><br>
<input type="submit" value="Upload" />
</form>
Java file:
UploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("username");
System.out.println(id); //returns null value
String password = request.getParameter("email");
System.out.println(password);//returns null value
For using file upload you get value only in form field.
request method not work in file upload
if (ServletFileUpload.isMultipartContent(request)) {
List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multipart) {
if (!item.isFormField();
{
//Your upload file code.
}
if (item.isFormField()) {
if (item.getFieldName().equals("username")) {
String id = item.getString();
}else if (item.getFieldName().equals("email")) {
String password = item.getString();
}
}
public class Relay extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String command = request.getParameter("command");
RequestDispatcher rd =request.getRequestDispatcher(command);
rd.forward(request, response);
System.out.println("Request forwarded to " + command + " servlet");
}
}
This is my Relay servlet, I'm sending data from this form
<form action="Relay" method="POST" enctype="multipart/form-data"> /
<input type="hidden" name="command" value="AddProduct" />
<input type="text" name="pname" value="" />
<input name="" type="submit" value="Add Product">
</form>
It is throwing a java.lang.NullPointerException.
But works fine when I remove this:
enctype="multipart/form-data"
Why do you need to add it then? Just keep it out.
If you need it in order to upload a file by <input type="file"> which you intend to add later on, then you should put #MultipartConfig annotation on your servlet, so that request.getParameter() will work and that all uploaded files can be retrieved by request.getPart().
#WebServlet("/Relay")
#MultipartConfig
public class Relay extends HttpServlet {
// ...
}
See also:
How to upload files to server using JSP/Servlet?
Parameters encoded with multipart/form-data are sent in POST body - not as regular request parameters, therefore can't be read using request.getParamter(...).
Check out Commons file upload package for multipart requests processing.
I am including this just for additional information for troubleshooting.
if you are stuck and want to know about what all parameters are coming through multipart request you can print all parameters using following code.
MultipartRequest multi = <Your code to retrieve multipart request goes here. Sorry but can not post code as I use proprietary APIs>
Enumeration en1 = multi.getParameterNames();
while (en1.hasMoreElements()) {
String strParamName = (String)en1.nextElement();
String[] strParamValues = multi.getParameterValues(strParamName);
for (int i = 0; i < strParamValues.length; i++) {
System.out.println(strParamName + "=" + strParamValues[i]);
}
}
remove the form tag and use
echo <?php form_open_multipart('Controller/function');
I got the same issue whenever I use enctype="multipart/form-data"
I didn't get the file name and when I remove that it was working fine
try it it worked for me