I need to upload an image from client to server using html type='file' which works fine,so far I could is to send file from client and receive on my servlet, but now I need to limit the image size in my servlet upto 2MB and if it's bigger than 2MB I need to send an error to client saying about the image size.
Here my servlet code that I receive sent image:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
MultipartRequest multipartRequest = new MultipartRequest(request, "D:\\");
out.print("Successfully Uploaded");
}
so far it does is to receive image and save it in D: directory, and I don't want to first save the image and then check image size, but to say something to MultipartRequest that if you received higher than 2MB send an error.
Thanks in advance:)
Since you haven't specified what is "MultipartRequest" class, I assume you are using oreilly package.
It has a public MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize) throws IOException constructor, which takes max file size parameter.
If the uploaded file size is more than maxPostSize, it will throw an IOException. You could probably catch this exception and return error response.
You can restrict the size of the uploaded file when creating a MultipartRequest instance.
MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory)
Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to the given directory, and limiting the upload size to 1 Megabyte.
MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory, int maxPostSize)
Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to the given directory, and limiting the upload size to the specified length.
Use this code on servlet and try it now
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ; `
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex);
}
file size is in bytes form so u can add max file size according to your requirements bytes to mb thanks
Related
I found this code to upload a file and it is working correctly.
<%# page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%# page import = "javax.servlet.http.*" %>
<%# page import = "org.apache.commons.fileupload.*" %>
<%# page import = "org.apache.commons.fileupload.disk.*" %>
<%# page import = "org.apache.commons.fileupload.servlet.*" %>
<%# page import = "org.apache.commons.io.output.*" %>
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload2");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex);
}
} else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
response.sendRedirect("clientupload.html");
%>
XML-file
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload2</param-name>
<param-value>
C:\Users\saurabh\Documents\NetBeansProjects\Amber_try\web\image\card\
</param-value>
</context-param>
I need to change the address like this
Amber_try\web\image\card\
but if I do this, it doesn't work, the code compiles but nothing gets
uploaded to the specified folder.
How should I change this address?
I need to upload a file on the server this is my project for the final year.
Totally new to programming please be very explanation.
I am making a website which will I upload on some server and will demonstrate this live(as buying a domain is easy and it will secure more marks) but when I will upload this on the server it will give the error.
Thanks in advance.
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
I want to avoid duplication while uploading file. If a file is updated then eventhough it has same name as which was uploaded previously, I should be able to upload that file on server.
I have written following servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("from").equals("upload")) {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(req)) {
PrintWriter writer = resp.getWriter();
writer.println("Request does not contain upload data");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// constructs the directory path to store upload file
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(req);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
System.out.println(f.format(storeFile.lastModified()));
System.out.println(storeFile.lastModified());
System.out.println(f.parse(f.format(storeFile.lastModified())));
File[] files = new File(
"C:\\bootcamp\\programs\\eclipse-jee-neon-RC3-win32-x86_64\\eclipse\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\excelFileManagement\\upload")
.listFiles();
int uploadFiles=0;
for (File file : files) {
if (fileName.equals(file.getName())) {
uploadFiles =1;
System.out.println("same");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:sss");
String currentFile = df.format(storeFile.lastModified());
String storedFile = df.format(file.lastModified());
System.out.println("currentFile" + currentFile + "storedFile" + storedFile);
if (currentFile.contains(storedFile)) {
System.out.println("Same file cannot be uploaded again");
getServletContext().getRequestDispatcher("/Error.jsp").forward(req, resp);
} else {
// saves the file on disk
item.write(storeFile);
System.out.println("Upload has been done successfully!");
// Reading excel file
ReadingExcelFile rd = new ReadingExcelFile();
rd.readExcel(filePath);
getServletC
ontext().getRequestDispatcher("/DisplayTables.jsp").forward(req, resp);
}
}
}
catch (Exception ex) {
System.out.println("There was an error: " + ex.getMessage());
}}
However, I am getting same last modified date and time for both the files. And if a new file is uploaded storeFile.lastModified() returns Thu Jan 01 05:30:00 IST 1970 value
Can you confirm what is actual lastModified date of the file already uploaded by OS explorer ?
Second thing in SimpleDateFormat constructor arg m stands for minutes and M stands for month.Also S stands for millsecond.So your correct code would be
SimpleDateFormat("yyyy-MM-dd hh:mm:S")
Can you try with these changes and check ?
I have tried to copy the tutorial from here JSP File Uploading. I am using Eclipse and tomcat, but when I run on the server I get the error:
An error occurred at line: 24 in the jsp file: /index.jsp
DiskFileItemFactory cannot be resolved to a type
21: String contentType = request.getContentType();
22: if ((contentType.indexOf("multipart/form-data") >= 0)) {
23:
24: DiskFileItemFactory factory = new DiskFileItemFactory();
25: // maximum size that will be stored in memory
26: factory.setSizeThreshold(maxMemSize);
27: // Location to save data that is larger than maxMemSize.
I have downloaded the commons fileupload and io packages and added the jars as external in the build path. The code is a direct copy from the tutorial with imports and everythingh, here is the full code from the link.
<%# page import="java.io.*,java.util.*, javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%# page import="org.apache.commons.fileupload.*" %>
<%# page import="org.apache.commons.fileupload.disk.*" %>
<%# page import="org.apache.commons.fileupload.servlet.*" %>
<%# page import="org.apache.commons.io.output.*" %>
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}else{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
You should copy jars to WEB-INF/lib. This is the only way to guarantee that the libraries will be on classpath when you run deployed web application.
Don't write this fileupload business logic in JSP file. Instead of use a servlet for file uploading. Example of such servlet you can find here.
Eclipse project structure:
Following is my complete code for uploading file to server using apache common upload. When I test this function in new project, it works. But when I integrated into my project, it's not working anymore. I found the problem in "List fileItems = upload.parseRequest(request);" fileItems there is zero while it should be 1. Is there some wat that I can solve this issue?
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
//isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>")y
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
When I test this function in new project, it works. But when I integrated into my project, it's not working anymore.
That's generally a sign that the library versions are different. If you're using maven, compare the dependency graphs below the apache common artifact so you can get your test project on the same version.
These are days that I'm banging my head on this problem and maybe you that certainly know more than me you can help me ....
Then I try to explain better.
I have a javascript file that through the library d3.js builds the html code pages and replaces it with the other code each part a different function ... The page will not charge (Ajax).
At some point I need to allow the user to upload an image to their profile picture so I make sure that the html code bait
<input type="file" id="file">
and a
<input type = "button" onclick = "javaScript: performAjaxSubmit ()">
PerformAjaxSubmit function () sends the data to a Java Servlet via a xmlHttpRequest level 2, which, from what I understand, can send not only strings but also more complex things such as files.
The function is as follows:
function performAjaxSubmit() {
var sampleFile = document.getElementById("file").files[0];
var formdata = new FormData();
formdata.append("sampleFile", sampleFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:8080/Prova/Upload", true);
xhr.send(formdata);
xhr.onload = function(e) {
if (this.status == 200) {
alert(this.responseText);
}
};
}
The code in the Servlet instead is this:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
System.out.println(request.getAttribute("username"));
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));
filePath="C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti";
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +"/"+
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
System.out.println(filePath +
fileName.substring(fileName.lastIndexOf("\\")+1));
file = new File( filePath +"/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
}
}
}catch(Exception ex) {
System.out.println(ex);
}
}
Now (sorry if the question is a bit long) it works but the problem is that the images are saved in the path that I have provided me with the command:
factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));
How do I then save it remotely? That is, once I load the site of such Altrevista, how do I make sure that they are not piĆ saved to C but in a folder in your project?
I hope I explained. I'm using Apache Tomcat v7.0.
Thanks in advance!
You can use ServletContext.getRealPath
This code returns <context root>/upload (depends on your deployment configuration)
request.getSession().getServletContext().getRealPath("/upload")