file not found exception, system can not specified image path - java

System cannot specified the file error is coming. I dont know why
I am using servlet and used file input stream in it to convert image in byte form..
public class Student extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String f=request.getParameter("U_Fname");
String l=request.getParameter("U_Lname");
String p=request.getParameter("U_Pswd");
String e=request.getParameter("U_Email");
String m=request.getParameter("U_Mobile");
String a=request.getParameter("U_Address");
String c=request.getParameter("U_Category");
String g=request.getParameter("U_Gender");
String d=request.getParameter("U_Dob");
String t=request.getParameter("U_Country");
String j=request.getParameter("U_Image");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","admin");
PreparedStatement ps=con.prepareStatement("insert into Registeruser values(?,?,?,?,?,?,?,?,?,?,?)");
FileInputStream fis=new FileInputStream(new File(j));
ps.setString(1,f);
ps.setString(2,l);
ps.setString(3,p);
ps.setString(4,e);
ps.setString(5,m);
ps.setString(6,a);
ps.setString(7,c);
ps.setString(8,g);
ps.setString(9,d);
ps.setString(10,t);
ps.setBinaryStream(11,fis);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully Registred...");
}catch(Exception e2)
{System.out.println(e2);}
out.close();
}
}
The system file cannot specified , java file not found exception

You can try the following. I assume that you are submitting the Image file not the Image path.
InputStream inputStream = null;
Part filePart = request.getPart("U_Image");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
if (inputStream != null) {
ps.setBlob(11, inputStream);
}

Related

servlet is showing java.io.FileNotFoundException: ?E:\guru99\test.txt (The filename, directory name, or volume label syntax is incorrect)

My servlet is showing this exception but the file exist at that location.
java.io.FileNotFoundException: ?E:\guru99\test.txt (The filename, directory name, or volume label syntax is incorrect)
Servlet Code,
#WebServlet(urlPatterns = {"/image_download"})
public class image_download extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String gurufile = "test.txt";
String gurupath = "‪E:\\guru99\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + gurufile + "\"");
FileInputStream fileInputStream = new FileInputStream(gurupath + gurufile);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I want to download the file from the link I provided.
Your issue is duplicate of this SO question
As when I tried to copy your code to my eclipse , I got same prompt about Save Problems. Somewhere there is an invalid character & string with that char can't be parsed into valid file path.
I manually retyped values for String gurufile & String gurupath instead of copy pasting your code & it worked successfully. Culprit seems String gurupath.
Second point is usage of try-with-resource ( though that has nothing to do with your issue ) instead of explicitly trying to close out resources,
response.setContentType("text/html");
String gurufile = "test.txt";
String gurupath = "D:\\guru99\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + gurufile + "\"");
try (FileInputStream fileInputStream = new FileInputStream(gurupath + gurufile);
PrintWriter out = response.getWriter();) {
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
}
Copy - paste my code to see if this resolves your problem.

MSWord File download issue using HttpServlet

i have implemented a servlet to download doc files available under my application classpath.
what happening is; file is downloading but ms-word is unable to open it property.
see the screenshot of ms-word:
Servlet implementation is as follows:
public class DownloadFileServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = "test.doc";
ClassPathResource resource = new ClassPathResource(File.separator + fileName);
ServletOutputStream sos = null;
FileInputStream fis = null;
try {
response.setContentType("application/msword");
response.setHeader("Content-disposition", "attachment; fileName=\"" + fileName + "\"" );
fis = new FileInputStream(new File(resource.getURI().getPath()));
byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(fis);
sos = response.getOutputStream();
sos.write(bytes);
sos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if( fis != null) {
fis.close();
}
if( sos != null) {
sos.close();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
i have tried almost all suggested Content Types for ms-word files. but still it is not working.
application/msword
application/ms-word
application/vnd.ms-word
Kindly suggest I'm making a mistake or is there any other way to achieve.
Note: i have tried almost all approaches available on SO.
Instead of reading, converting to byte[] simply write directly to the OutputStream. You shouldn't close the OutputStream as that is being handled by the container for you.
I would rewrite your servlet method to more or less the following (also why is it a servlet and not a (#)Controller?
protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = "test.doc";
ClassPathResource resource = new ClassPathResource(File.separator + fileName);
InputStream input = resource.getInputStream();
try {
response.setContentType("application/msword");
response.setHeader("Content-disposition", "attachment; fileName=\"" + fileName + "\"" );
org.springframework.util.StreamUtils.copy(input, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOEXception ie) {}
}
}
}
i do not know what a ClassPathResource class does. hence modified the code a bit.
ClassLoader clsLoader = Thread.currentThread().getContextClassLoader();
InputStream is = clsLoader.getResourceAsStream("test.doc");
and in the try block use:
byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(is);
this should work fine. i placed the doc in the classpath. modify it to suit your needs.
Regarding the mime mapping, open your server properties and you will find a list of mime mapping. Eg. in eclipse for tomcat, just double click on the server and you should be able to find the mime mapping list there. application/msword worked fine

Download image on clicking an image

I want to download image on click. I had set content type but I couldn't write image in response. In controller I get URL of image.
String image=myimageUrl;
File file = new File(image);
String contentType = getServletContext().getMimeType(file.getName());
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
For writing into response I used this code
DataInputStream input = new DataInputStream(new FileInputStream(file));
ServletOutputStream output = response.getOutputStream();
Here input returns null.
How to resolve this problem?
Please check following code.
for uploading image into database.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String path=request.getParameter("h2");
out.println(path);
Connection connection=null;
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
File image = new File(path);
psmnt = connection.prepareStatement("insert into new1(id,imagepath)"+"values(?,?)");
String s1=request.getParameter("h1");
psmnt.setString(1,s1);
fis = new FileInputStream(image);
psmnt.setBinaryStream(2, (InputStream)fis, (int)(image.length()));
int s = psmnt.executeUpdate();
if(s>0) {
out.println("Uploaded successfully !");
}
else {
out.println("unsucessfull to upload image.");
}
}
catch (Exception ex) {
System.out.println("Found some error : "+ex);
}
and for downloading image.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection connection = null;
ResultSet rs = null;
PreparedStatement psmnt = null;
InputStream sImage;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
psmnt = connection.prepareStatement("SELECT imagepath FROM new1 WHERE id = ?");
psmnt.setString(1, "23");
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
//response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}
}
}
catch(Exception ex){
// out.println("error :"+ex);
}
}

File reading issue in servlet

I have to read a file using servlet.here is the code iam using.but file is not reading using this code.Always printing File contains null value-----------------:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/html");
String filename = "D/root.properties";
ServletContext context = getServletContext();
InputStream inp = context.getResourceAsStream(filename);
if (inp != null) {
InputStreamReader isr = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(isr);
PrintWriter pw = response.getWriter();
String text = "";
while ((text = reader.readLine()) != null) {
}
} else {
System.out.println("File contains null value-----------------");
}
} catch(Exception e) {
System.out.println("Rxpn............................................."+e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
javadoc to the rescue :
java.net.URL getResource(java.lang.String path)
throws java.net.MalformedURLException
Returns a URL to the resource that is mapped to the given path.
The path must begin with a / and is interpreted as relative to the current context root, or relative to the /META-INF/resources directory
of a JAR file inside the web application's /WEB-INF/lib directory.
This method will first search the document root of the web application
for the requested resource, before searching any of the JAR files
inside /WEB-INF/lib. The order in which the JAR files inside
/WEB-INF/lib are searched is undefined.
If you want to read from a resource in the web app, use a path as indicated above. If you want to read from the file system, use file IO (and the correct file name): new FileInputStream("D:/root.properties")
Use following code.
With this you can read file
File file = new File("Filepath");
try {
if (file.exists()) {
BufferedReader objBufferReader = new BufferedReader(
new FileReader(file));
ArrayList<String> arrListString = new ArrayList<String>();
String sLine = "";
int iCount = 0;
while ((sLine = objBufferReader.readLine()) != null) {
arrListString.add(sLine);
}
objBufferReader.close();
for (iCount = 0; iCount < arrListString.size(); iCount++) {
if (iCount == 0) {
createTable(arrListString.get(iCount).trim());
} else {
insertIntoTable(arrListString.get(iCount).trim());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream file = new FileInputStream("c:\\hi.txt");
DataInputStream input = new DataInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String text = "";
while ((text = br.readLine()) != null) {
System.out.println(text);
}
}
}
Please try the above code sample. I think in your code , file is not found. Please give the file path in the above code and try.

Why does my browser receive no data when OutputStream.flush() is called?

I have a servlet which just read a file and send it to the browser.
The file is readen correctly, but on OutputStream.flush(), the browser receive no data.
Firefox says :
"Corrupted Content Error
The page you are trying to view cannot be shown because an error in the data transmission was detected.". Firebug shows the status "Aborted".
IE open or save an empty file.
I tried little or big files.
The code is :
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Use a ServletOutputStream because we may pass binary information
response.reset();
OutputStream out = response.getOutputStream();
// Get the file to view
String file = request.getParameter("path");
// Get and set the type and size of the file
String contentType = getServletContext().getMimeType(file);
response.setContentType(contentType);
long fileSize = (new File(file)).length();
response.setHeader("Content-Length:", "" + fileSize);
File f = new File(file);
response.setHeader("Content-Disposition", "attachment;filename="+f.getName());
response.setContentLength((int) fileSize);
// Return the file
try {
returnFile(file, out, response);
} catch (Exception e) {
Logger.getLogger(AffichageItemsServlet.class).error("", e);
} finally {
out.close();
}
}
// Send the contents of the file to the output stream
public static void returnFile(String filename, OutputStream out, HttpServletResponse resp)
throws FileNotFoundException, IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
byte[] buff = new byte[8* 1024];
int nbRead = 0;
while ((nbRead = fis.read(buff, 0, buff.length)) !=-1) {
out.write(buff, 0, nbRead);
}
out.flush();
} finally {
if (fis != null) {
fis.close();
}
}
}
The response is sent on "out.flush".
Any idea ?
For one thing, remove this line (you call setContentLength() below that):
response.setHeader("Content-Length:", "" + fileSize);
Also, you might try moving the getOutputStream() call to just before you start using the stream.

Categories

Resources