Okay i will give you the shoretest and easiest solution
The HTML form in tut-install/examples/web/fileupload/web/index.html is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="upload" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" /> <br/>
Destination:
<input type="text" value="/tmp" name="destination"/>
</br>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
A POST request method is used when the client needs to send data to the server as part of the request, such as when uploading a file or submitting a completed form. In contrast, a GET request method sends a URL and headers only to the server, whereas POST requests also include a message body. This allows arbitrary-length data of any type to be sent to the server. A header field in the POST request usually indicates the message body’s Internet media type.
When submitting a form, the browser streams the content in, combining all parts, with each part representing a field of a form. Parts are named after the input elements and are separated from each other with string delimiters named boundary.
This is what submitted data from the fileupload form looks like, after selecting sample.txt as the file that will be uploaded to the tmp directory on the local file system:
POST /fileupload/upload HTTP/1.1
Host: localhost:8080
Content-Type: multipart/form-data;
boundary=---------------------------263081694432439
Content-Length: 441
-----------------------------263081694432439
Content-Disposition: form-data; name="file"; filename="sample.txt"
Content-Type: text/plain
Data from sample file
-----------------------------263081694432439
Content-Disposition: form-data; name="destination"
/tmp
-----------------------------263081694432439
Content-Disposition: form-data; name="upload"
Upload
-----------------------------263081694432439--
The servlet FileUploadServlet.java can be found in the tut-install/examples/web/fileupload/src/java/fileupload/ directory. The servlet begins as follows:
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private final static Logger LOGGER =
Logger.getLogger(FileUploadServlet.class.getCanonicalName());
The @WebServlet annotation uses the urlPatterns property to define servlet mappings.
The @MultipartConfig annotation indicates that the servlet expects requests to made using the multipart/form-data MIME type.
The processRequest method retrieves the destination and file part from the request, then calls the getFileName method to retrieve the file name from the file part. The method then creates a FileOutputStream and copies the file to the specified destination. The error-handling section of the method catches and handles some of the most common reasons why a file would not be found. The processRequest and getFileName methods look like this:
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
new Object[]{fne.getMessage()});
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
## Code to Add File to a folder Dynamically ##
String filePath = "D:\\folder1Name\\folder2Name\\";
if (request.getPart("file") != null) {
if (request.getPart("file").getSize() != 0) {
System.out.println(UName + "UName" + "LoopilKeri");
final Part filePart = request.getPart("file");
String folderName = filePath + UName + "//file";//path;
final String fileName = getFileName(filePart);
//
File file = new File(folderName);
if (!file.exists()) {
file.mkdirs();
}
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(folderName + File.separator
+ fileName));
filecontent = filePart.getInputStream();
StringBuilder sb = new StringBuilder();
int read = 0;
final byte[] bytes = new byte[1024];
// byte[] byte1 = new byte[1024];
// byte1=IOUtils.toByteArray(filecontent);
// System.out.println(byte1.toString());
while ((read = filecontent.read(bytes)) != -1) {
sb.append(bytes);
System.out.println(bytes);
System.out.println(bytes + "0here" + read);
out.write(bytes, 0, read);
}
// writer.println("New file " + fileName + " created at " + folderName);
System.out.println("###########################################################################");
System.out.println(sb.toString());
request.setAttribute("f1", folderName);
request.setAttribute("f2", fileName);
// request.setAttribute("f", byte1);
System.out.println(sb);
System.out.println("###########################################################################");
ServletContext se = this.getServletContext();
// RequestDispatcher rd =se.getRequestDispatcher("/NewServlet");
// rd.forward(request, response);
// LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
// new Object[]{fileName, folderName});
} catch (FileNotFoundException fne) {
// writer.println("You either did not specify a file to upload or are "
// + "trying to upload a file to a protected or nonexistent "
// + "location.");
// writer.println("<br/> ERROR: " + fne.getMessage());
LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
new Object[]{fne.getMessage()});
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
}