How to upload file using JSP / Servlet?
Technology world moving fast as a speed of light. Its getting change day by day. Web application is build under the MVC ( Model-View-Controller) model. Colleges still using servlet in study. In below article we'll discuss how you can manage your web application to upload files.
Required .jar files
- commons-io-2.0.jar ( http://commons.apache.org/io/download_io.cgi )
- commons-fileupload-1.2.2.jar ( http://commons.apache.org/fileupload/download_fileupload.cgi )
import bean.setNotification; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils;
All above packages you have to import in you servlet. Below code is for file upload in servlet. File upload directory is "/upload/"
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/upload/");
//Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(FileUploadExample.class.getName()).log(Level.SEVERE, null, ex);
//Change above line replace FileUploadExample with your file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
}
/*
* If you want to pass some other data from JSP page. You can access then in this way.
* For each field you have do create if like below.
* if (fileItemTemp.getFieldName().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString();
* }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
//If you want to limit the file size. Here 30MB file size is allowed you can change it
if (filesize > 30.0) {
//Pass error message in session.
setNotification _sN = new setNotification();
_sN.setError("File size can't be more than 30MB");
session.setAttribute("error", _sN);
} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../upload/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"), fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("error", _sN);
}
}
}
String referer = request.getHeader("Referer");
response.sendRedirect(referer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
Now notification class to shows the message to users. Use the below code.
public class setNotification {
private String Error="";
public String getError() {
return Error;
}
public void setError(String Error) {
this.Error = Error;
}
}
The JSP file. Change the servlet name in action (form). Change package import bean.setNotification.
<%@page import="bean.setNotification"%>
<%
setNotification _sN = new setNotification();
if (session.getAttribute("error") != null) {
_sN = (setNotification) session.getAttribute("error");
}
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Example</title>
<link type="text/css" href="css/bundle.css" rel="StyleSheet"/>
</head>
<body>
<center>
<div class="signal_box" style="width: 400px;height: 150px">
<div class="head">File Upload - javaQuery.com</div>
<form action="FileUploadExample" method="post" enctype="multipart/form-data">
<input type="file" name="myFile"/><br/>
<input type="submit" value="Upload it"/>
</form>
<br/>
<%=_sN.getError()%>
<%_sN.setError("");%>
</div>
</center>
</body>
</html>
So this is file upload example in servlet.....
0 comments :