I am usning the following code to upload a servlet. However it is repeatedly throwing an error..
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
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>");
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("D:\\tmp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
System.out.println("hello ");
try{
// Parse the request to get file items.
System.out.println("hello ");
List<FileItem> 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("brilliant ");
}
}
}
however the error i am getting is
SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
its also not going to expception block:(
I tried printing the stacktrace..didn't work..as for configuration is concerned i believe its fine..i gace sysout statements inside the dopost method it printed fine..to the point where i have delcared LIST..after that its going ahead
The error appears to be happening before even calling your servlet. It's probably a configuration issue.
Related
I am trying to download a file from my web application in an ActionForward java class. I have looked at many examples to try different solutions but none have worked so far. My knowledge is limited and have spent a good amount of time to get this to work.
From my jsp page a link hits an action in my struts config which takes the thread to an ActionForward return type method on a java class.
I then take the passed in file name and grab it from an amazon s3 bucket. With the file downloaded from the s3 bucket I now have the file bytes[].
I need to then have the file download to the local machine as most files do (appearing in the downloads folder and the web showing the download at the bottom bar of the page)
After following some examples I kept getting this error
Servlet Exception - getOutputStream() has already been called for this
response
I got past the error by doing
response.getOutputStream().write
Instead of creating a new OutputStream like this
OutputStream out = response.getOutputStream();
Now it runs without errors but no file gets downloaded.
Here is the java file I am attempting to do this in.
As you can see in the file below is a commented out DownloadServlet class which I tried as another attempt. I did this because a lot of the examples have classes the extends HttpServlet which I made DownloadServlet extend but it made no difference.
package com.tc.fms.actions;
import com.sun.media.jai.util.PropertyUtil;
import com.tc.fw.User;
import org.apache.commons.beanutils.PropertyUtils;
import java.io.*;
import java.io.File;
import java.util.ArrayList;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tc.fw.actions.BaseAction;
import org.apache.struts.upload.FormFile;
import io.isfs.utils.ObjectUtils;
import com.tc.fw.*;
import com.tc.fms.*;
import com.tc.fms.service.*;
public class FileDownloadAction extends BaseAction {
private static ObjectUtils objectUtils = new ObjectUtils();
private final int ARBITARY_SIZE = 1048;
public ActionForward performWork(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("In File Download Action");
ActionMessages errors = new ActionMessages();
User user = (User)request.getSession().getAttribute(User.lookupKey);
String fileName = (String) PropertyUtils.getSimpleProperty(form, "fileName");
String outboundDir = (String) PropertyUtils.getSimpleProperty(form, "outboundDir");
System.out.println("File Dir: " + outboundDir + " File Name: " + fileName);
try{
try {
// Get file from amazon
byte[] fileBytes = objectUtils.getFileDavid(outboundDir, fileName);
if (fileBytes != null) {
java.io.File file = File.createTempFile(fileName.substring(0, fileName.lastIndexOf(".") - 1), fileName.substring(fileName.lastIndexOf(".")));
FileOutputStream fileOuputStream = new FileOutputStream(file);
fileOuputStream.write(fileBytes);
try {
/* DownloadServlet downloadServlet = new DownloadServlet();
downloadServlet.doGet(request, response, file);*/
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
InputStream in = new FileInputStream(file);
/*OutputStream out = response.getOutputStream();*/
byte[] buffer = new byte[ARBITARY_SIZE];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
response.getOutputStream().write(buffer, 0, numBytesRead);
}
} catch (Exception e) {
System.out.println("OutputStream EROOR: " + e);
}
} else {
System.out.println("File Bytes Are Null");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.no.file.found"));
saveErrors(request, errors);
return mapping.findForward("failure");
// Failed
}
} catch (Exception eee){
System.out.println("Failed in AWS ERROR: " + eee);
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.failed"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
}catch (Exception ee){
System.out.println("Failed in global try");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.failed"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
return mapping.findForward("success");
}
}
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 5 years ago.
I am trying to upload a file through my web application and read the uploaded file. First I can upload it to my desktop. But this is not what I want. I want to create a directory named file (you can see in picture) inside my project explorer in Eclipse. And then upload the file to there. I tried many ways to give the path but it always giving me this exception : File Upload Failed due to java.io.FileNotFoundException.Here is my project explorer.enter image description here
https://ibb.co/niTaN6 here is the image
And here is my code.
package com.fileupload;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;
#WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "/GraphCoverage/file/";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// process only if its multipart content
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List<FileItem> multiparts = upload.parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
// File uploaded successfully
request.setAttribute("message", "Your file has been uploaded!");
}
catch (Exception e)
{
request.setAttribute("message", "File Upload Failed due to " + e);
}
} else
{
request.setAttribute("message", "This Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Hi chalesea23 you need to provide full system path like "C:/Users/abc/eclipse-workspace/Test/file", then it will work. Because a folder in your eclipse is nothing but a folder on your PC.
Below is working for me.
package com.java;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;
#WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "C:/Users/abc/eclipse-workspace/Test/file";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// process only if its multipart content
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List<FileItem> multiparts = upload.parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
// File uploaded successfully
request.setAttribute("message", "Your file has been uploaded!");
} catch (Exception e) {
request.setAttribute("message", "File Upload Failed due to " + e);
}
} else {
request.setAttribute("message", "This Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Servlet Code :
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class profile_photo extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession ses=request.getSession();
String email = (String)ses.getAttribute("ses_email");
String imgLen="";
Connection cn;
PreparedStatement ps;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:sm","system","gecbsp");
ps=cn.prepareStatement("select photo_loc from smreg3 where email = "+
"'"+email+"'");
ResultSet rs = ps.executeQuery();
if(rs.next()){
imgLen = rs.getString(1);
System.out.println(imgLen.length());
}
ps=cn.prepareStatement("select photo_loc from smreg3 where email = "+
"'"+email+"'");
ResultSet rs2 = ps.executeQuery();
if(rs2.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs2.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
ps.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Jsp code :
<img src="${pageContext.request.contextPath}/profile_photo" />
Error :
java.lang.IllegalStateException: getWriter() has already been called for this response
at org.apache.catalina.connector.Response.getOutputStream(Response.java:573)
at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:183)
at profile_photo.doGet(profile_photo.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)
Questions:
How to retrieve image in JSP from ImageServlet?
Is the above method correct way to retrieve image from database? Or is there better way?
As you declare out but don't seem to use it, you should probably remove the line
PrintWriter out = response.getWriter();
You can not call getOutputStream() on a response once you did a call to getWriter().
// try below change
response.setContentType("application/octet-stream");
response.setContentLength(len);
OutputStream outputStream = response.getOutputStream();
outputStream.write(rb,0,len);
outputStream.flush();
HTTP Status 500 -
type Exception report
Message
description The server encountered an internal error () that prevented it from fulfilling this request.
Exception:
javax.servlet.ServletException: Servlet execution threw an exception
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Root cause:
java.lang.NoSuchMethodError: org.apache.commons.fileupload.FileUploadBase.isMultipartContent(Lorg/apache/commons/fileupload/RequestContext;)Z
org.apache.commons.fileupload.servlet.ServletFileUpload.isMultipartContent(ServletFileUpload.java:71)
WindsofChange.User_FileEncrypt.doPost(User_FileEncrypt.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.14 logs.
Apache Tomcat/7.0.14
Here is my Code:
public class ServletDemo extends HttpServlet {
private static final byte[] initialization_vector = { 22, 33, 11, 44, 55, 99, 66, 77 };
File encryptedPath, uploadedFile;
String fileName;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
//filesize=item.getSize(); get filesize in bytes
if (!item.isFormField())
{
fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
//if uploads folder not exists create
if (!path.exists())
{
boolean status = path.mkdirs();
}
uploadedFile = new File(path + "/" + fileName);
encryptedPath = new File(path + "/encrypted" + fileName);
out.println(uploadedFile.getAbsolutePath());
try{
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
}catch(Exception e){}
out.println("File Uploaded Successfully....:-)");
}
else
{
String abc = item.getString();
}
}
}catch(Exception e){e.printStackTrace();}
}
else
{
out.println("Not Multipart");
}
}
}
I think the problem have nothing to do with your code.May be the reason of the problem is Jar.
Adjust the class loading sequence,would be solve the problem。
I have created dynamic webproject and i am using following code to upload the image and retrieve from the same location.now when i am trying to run the application in external browser it shows rectangle box instead of image.getting loaded in external web browser gives an error.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.sql.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.*;
public class UploadImage extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("request: " + request);
if (!isMultipart) {
System.out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
System.out.println("items: " + items);
}
catch (FileUploadException e)
{
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
String name = item.getFieldName();
System.out.println("name: " + name);
String value = item.getString();
System.out.println("value: " + value);
}
else
{
try
{
String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
System.out.println("Text before replacing is:-"+ itemName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find())
{
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
System.out.println("domainName: " + domainName);
String finalimage = buffer.toString() + "_" + r+ domainName;
System.out.println("Final Image===" + finalimage);
File savedFile = new File("D:\\test1\\" + "images\\"+ finalimage);
item.write(savedFile);
out.println("<html>");
out.println("<body>");
out.println("<table><tr><td>");
out.println("<img src=D:\\test1\\images\\" + finalimage+ ">");
out.println("</td></tr></table>");
Connection conn = null;
String url = "jdbc:oracle:thin:#//localhost:1521/erp";
String username = "system";
String userPassword = "manager";
String strQuery = null;
try
{
System.out.println("itemName::::: " + itemName);
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username,userPassword);
Statement st = conn.createStatement();
strQuery = "insert into testimage values('"+ finalimage + "')";
int rs = st.executeUpdate(strQuery);
System.out.println("Query Executed Successfully++++++++++++++");
out.println("image inserted successfully");
out.println("</body>");
out.println("</html>");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
conn.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
}
The process is roughly as follows:
Enduser requests a web page on a certain URL.
Webbrowser sends HTTP request to webserver on the given URL.
Webserver retrieves HTTP request and returns the desired web page as HTTP response.
Webbrowser retrieves HTTP response in flavor of HTML code.
Webbrowser parses HTML code in order to present it and encounters an <img> element.
Webbrowser attempts to download the image from the location as specified in its src attribute.
And there is where it fails. You specified a fixed local disk file system path which is only valid if the webbrowser runs at physically the same machine as the webserver (as would occur in development environment, but absolutely not in production environment). You can't and shouldn't expect that the enduser has the desired image at exactly the given location of his local disk file system. Even more, you can't and shouldn't expect that the enduser has a D: disk, let alone that the enduser is also running Windows.
You should instead be specifying a fullworthy URL in image's src attribute. Exactly the one as you would enter in webbrowser's address bar in order to see the image, starting with a http:// or https:// scheme.
There are several ways to achieve this, the two most popular ways are:
Expose the upload folder as a virtual host. This is to be done in server config. You didn't tell which one you're using, but let's assume that it's Tomcat like as many starters would use: open /conf/server.xml file and add the following element to the <Host> element:
<Context docBase="D:\test1\images" path="/images" />
The docBase specifies the root folder where all files reside and the path specifies the context path which you would see after the domain part in the URL. This way the images will be accessible through http://example.com/images/....
out.println("<img src=\"/images/" + finalimage+ "\">");
Create a simple servlet which reads the image from disk and writes it to the response after having set the desired response headers telling the browser about the file content type, length and disposition so that the browser knows how to deal with it:
#WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = URLDecoder.decode(request.getPathInfo(), "UTF-8");
File file = new File("D:\\test1\\images", filename);
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
Files.copy(file.toPath(), response.getOutputStream());
}
}
Also this way the images will be accessible through http://example.com/images/....
out.println("<img src=\"/images/" + finalimage+ "\">");
Unrelated to the concrete problem, emitting HTML in a servlet is a very poor practice. You should use JSP for that. See also the Coding style and recommendations section of our servlets wiki page.
Have you further also thought about uploaded images which happen to have the same file name as an existing uploaded image?