-1

so all i want t do is a simple form which transfer text and image. For now, i can't do both at the same time !

Here is a simple form code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<center>
<h1>File Upload</h1>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="text" name="CaptionBox" />
<input type="file" name="photo" />
<input type="submit" />
</form>
</center>
</body>
</html>

This code give me this error:

java.io.IOException: java.io.FileNotFoundException: C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles (Access denied) 

But if a put away the text input and let only the file input, it works! And i can't figure out why !

Here is the servlet code:

@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet{

/**
 * Name of the directory where uploaded files will be saved, relative to
 * the web application directory.
 */
private static final String SAVE_DIR = "uploadFiles";

/**
 * handles file upload
 */
protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    EventUtil.addImage(request);
    request.setAttribute("message", "Upload has been done successfully!");
    getServletContext().getRequestDispatcher("/message.jsp").forward(
            request, response);
}

}

And finally the Eventutil class:

package com.utils;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

public class EventUtil {

private static final String SAVE_DIR = "uploadFiles";

public static void addImage(HttpServletRequest request) throws IOException, ServletException{
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String savePath = appPath + File.separator + SAVE_DIR;
    System.out.println(savePath);

    // creates the save directory if it does not exists
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    for (Part part : request.getParts()) {
        String fileName = extractFileName(part);
        part.write(savePath + File.separator + fileName);
    }
}

private static String extractFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    String[] items = contentDisp.split(";");
    for (String s : items) {
        if (s.trim().startsWith("filename")) {
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        }
    }
    return "";
} 
}

Thanks !

Edit: StackTrace:

java.io.FileNotFoundException: C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles (Accès refusé)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.<init>(Unknown Source)
java.io.FileOutputStream.<init>(Unknown Source)
org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:394)
com.utils.EventUtil.addImage(EventUtil.java:28)
com.servlets.UploadServlet.doPost(UploadServlet.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
adamine
  • 105
  • 2
  • 8
  • It's *always* easier for us to help if you include the stacktrace, but did you check to see if `C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles` exists? If not, is the error from `mkdir()` (see stacktrace) and does the parent directory (`maroc_events`) exist? – Andreas May 28 '16 at 23:05
  • yes it exists, as i sayed the image is uploaded susccesfuly when there is no text input @Andreas – adamine May 28 '16 at 23:08
  • Also, you should use the new `Path` instead of the old `File`. One reason is that it provides better error messages. – Andreas May 28 '16 at 23:08

1 Answers1

0

The write() method throws the error because ...\maro‌​c_events\uploadFiles is a directory, and you cannot write to a directory.

You can write to a file in that directory, but that would require a filename. Very likely, fileName is blank.

Not sure, but I believe getParts() also return non-file parts, which means it also returns a part for the CaptionBox field. Try printing part.getName() to check.

Since you only expect one file anyway, use request.getPart("photo") instead of looping.

Andreas
  • 154,647
  • 11
  • 152
  • 247