not able to use jquery ajax FormData with servlet - java

I was trying to make a ajax request to servlet for uploading images using jquery ajax FormData. But I am always getting error response back from servlet. Below is my code:
JSP file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>File Upload</title>
<script>
function hitThis(){
alert("hello");
var form1 = document.getElementById("form1");
$.ajax( {
url: 'UploadDocs',
type: 'POST',
data: new FormData( form1 ),
processData: false,
contentType: false,
success: function(response) {
alert("success : ");
},
error: function(xhr) {
alert("error : "+JSON.stringify(xhr));
//Do Something to handle error
}
} );
}
</script>
</head>
<body>
<center>
<h1>File Upload</h1>
<form id="form1" class="form-inline" onsubmit="hitThis();">
Amount : <input type="text" value="232" name="amount"/><br>
Select file to upload: <input type="file" name="file" size="60" /><br />
Select file to upload: <input type="file" name="file" size="60" /><br />
<br /> <input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
Servlet
package org.wpits.ussd;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.wpits.service.DbService;
import org.wpits.ussd.beans.UserDocs;
/**
* Servlet implementation class UploadDocs
*/
#WebServlet("/UploadDocs")
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
public class UploadDocs extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbService dbService = new DbService();
private String filePath;
public UploadDocs() {
super();
}
#Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
filePath = getServletContext().getInitParameter("file-upload");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String savePath = filePath;
String amount = request.getParameter("amount");
System.out.println(amount);
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
if(fileName!=null && !fileName.equals("")){
InputStream is = part.getInputStream();
File f = new File(savePath+File.separator+fileName);
copyInputStreamToFile(is,f);
}
}
}
private void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024*1024*10];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private 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 "";
}
}
I am able to write images on described directory path. But the problem is, that I am always getting redirected to ajax's error response. Also, whenever I am restarting the tomcat server and trying to upload files, I am getting "java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly" On second attempt just after the first attempt failed due to error, above written code is able to write files but throwing response to error function of Ajax. Where am I making mistake? It would be very helpful if some one could resolve my problem.

Use this format to fire ajax.
//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
enctype:"multipart/form-data",
url: "uploadCsvData",
data: fileContent,
processData: false,
contentType: false,
success: function(response) {
}
});

the problem in above code was only that I was using onsubmit() and input type="submit" in my form. That has to be replaced with -- removing onsubmit event and applying onclick event to button instead of input type = "submit". Ajax gets mismatched when combined with basic form.

Related

How to convert absolute path to a relative path so that it can be referenced from an img tag? java web

Creating a web application that lets users upload images.
The code works but having trouble understanding how to get the images in a relative path so that it can be referenced from an img src="" tag?
So far the code takes the multipart request and stores the file in an absolute path on server but this cannot be referenced from an < img > tag..
Any ideas on how to go about this?
UploadFile.java (servlet)
package userServlets;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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;
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
#WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private boolean isMultipart;
private static final long serialVersionUID = 1L;
public UploadFile() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get session
HttpSession session = request.getSession();
// get the save location for files that user uploads to web app
String appPath = request.getServletContext().getRealPath("/uploads");
// get the name of the currently logged in user
String user = session.getAttribute("loggedInUser").toString();
// create the user's own folder in uploads folder of server.
String directory = appPath + File.separator + user;
File fileSaveDir = new File(directory);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
// get the path of the users folder location as a file
File uploads = new File(
request.getSession().getServletContext().getRealPath("/uploads" + File.separator + user));
// Check if request is multipart, if not, sends user back to uplaod page
// (test.jsp)
isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
// Suspicious looking stuff not too sure of but works i guess :/
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(uploads);
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// iterates over form's fields
for (FileItem item : formItems) {
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
long sizeInBytes = item.getSize();
String filePath = uploads + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
request.setAttribute("message", "Upload has been done successfully!");
request.setAttribute("filename", fileName);
// *STORE THIS IN DATABASE
request.setAttribute("filepath", filePath);
request.setAttribute("filesize", sizeInBytes);
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
request.setAttribute("directory", directory);
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
}
}
test.jsp (upload form)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<div class="jumbotron">
<div class="container">
<form method="post" enctype="multipart/form-data" action="UploadFile">
<input type="text" name="description" /> <input type="file"
name="file" /> <input type="submit" />
</form>
</div>
</div>
<h1>"${directory}"</h1>
<h1>"${message}"</h1>
<h1>"${filepath}"</h1>
<h1>"${filename}"</h1>
<h1>"${filetype}"</h1>
<h1>"${filesize}"</h1>
<img src="${filepath}">
<hr />
<div class="jumbotron">
<img alt="" src="hmmmmmm">
</div>
</body>
</html>
Figured it out after reading this link
If you have full control over the images folder, then just drop the
folder with all images, e.g. /images directly in servletcontainer's
deploy folder, such as the /webapps folder in case of Tomcat and
/domains/domain1/applications folder in case of GlassFish. No further
configuration is necessary.
literally drag and drop the file into the web application folder in your ide.
then you do this

AWS S3 returns "POST 400 bad request" for fileupload using plupload

I am trying to upload directly to AWS S3 with the help of plupload. I am using
https://github.com/moxiecode/plupload/blob/master/examples/jquery/s3.php and
https://github.com/moxiecode/plupload/wiki/Upload-to-Amazon-S3
as references.
But i am doing it with JSP and Servlet.
when i try to upload a file , it displays "server responded with status of 400- bad request".
here is my files :
upload.jsp ::
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>test</title>
<link rel="stylesheet" type="text/css" href="plupload/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css" media="screen" />
</head>
<body>
<div>
<div style="width: 750px; margin: 0px auto">
<div id="uploader">
<p> Flash, Silverlight, Gears, BrowserPlus HTML5 .</p>
</div>
<input type="button" value="Clear" id="clear"/>
</div>
</div>
<script type="text/javascript" src="js/jquery.min.js" ></script>
<script type="text/javascript" src="plupload/plupload.full.js"></script>
<script type="text/javascript" src="plupload/jquery.plupload.queue/jquery.plupload.queue.js"></script>
<!-- <script type="text/javascript" src="plupload/i18n/cn.js"></script> -->
<script >
/* Convert divs to queue widgets when the DOM is ready */
$(function(){
//ajax call to servlet for details
$.ajax({
type : "POST",
//dataType : "text" ,
url : "UploadCon2",
success : function(data)
{
plupload(data);
}
});
function plupload(data){
var flag_arr = data.split(" ");
var bucket = flag_arr[0] ;
var policy = flag_arr[1] ;
var signature = flag_arr[2] ;
var access_key_id = flag_arr[3];
alert(signature);
$("#uploader").pluploadQueue({
// General settings
runtimes : 'html5,gears,browserplus,silverlight,flash,html4',
unique_names : true,
// Flash settings
flash_swf_url : 'plupload/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url : 'plupload/plupload.silverlight.xap',
url : 'http://'+bucket+'.s3.amazonaws.com/',
//url : 'http://s3.amazonaws.com/'+bucket+'/',
multipart: true,
multipart_params: {
'key': '${filename}', // use filename as a key
'Filename': '${filename}', // adding this to keep consistency across the runtimes
'acl': 'public-read',
'success_action_redirect' : 'http://localhost/' ,
'Content-Type': '',
'x-amz-credential' : 'MYACCESSKEY/20160211/us-east-1/s3/aws4_request',
'x-amz-algorithm':'AWS4-HMAC-SHA256',
'x-amz-date' : '20160211T000000Z',
'policy': policy,
'x-amz-signature': signature,
},
});
}
plupload();
$('#clear').click(function(){
plupload();
});
});
</script>
</body>
</html>
servlet ::
UploadCon2.java
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Hex;
import org.aspectj.weaver.patterns.ThrowsPattern;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.util.Base64;
import com.fasterxml.jackson.core.JsonEncoding;
/**
* Servlet implementation class UploadCon2
*/
#WebServlet("/UploadCon2")
#MultipartConfig
public class UploadCon2 extends HttpServlet {
private static final long serialVersionUID = 1L;
// private static final String JSON = null;
/**
* #see HttpServlet#HttpServlet()
*/
public UploadCon2() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String bucketName = "thehexa4";
String access_key_id = "myaccesskey";
String secret_access_key = "secretaccesskey";
String policy_doc =
"{\"expiration\": \"2016-12-30T12:00:00.000Z\"," +
"\"conditions\": [" +
"{\"bucket\": \"thehexa4\"}," +
"[\"starts-with\", \"$key\", \"\"]," +
"{\"acl\": \"public-read\"}," +
"{\"success_action_redirect\": \"http://localhost/\"}," +
"[\"starts-with\", \"$Content-Type\", \"\"]," +
"[\"content-length-range\", 0, 10485760]" +
"{\"x-amz-credential\": \"myaccesskey/20160211/us-east-1/s3/aws4_request\"}," +
"{\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"}," +
"{\"x-amz-date\": \"20160211T000000Z\" }" +
"]" +
"}";
System.out.print(policy_doc);
// Calculate policy and signature values from the given policy document and AWS credentials.
String policy = new String(Base64.encode(policy_doc.getBytes("UTF-8")), "ASCII");
//HMAC SHA 256 calculation
String signingkey = "";
String signature = "";
try {
signingkey = getSignatureKey(secret_access_key,"20160211" , "us-east-1", "s3").toString();
//signature = Base64.encodeAsString((HmacSHA256(signingkey, policy.getBytes())));
signature = Hex.encodeHexString(HmacSHA256(signingkey, policy.getBytes()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out = response.getWriter();
out.write(bucketName+" ");
out.write(policy+" ");
out.write(signature+" ");
out.write(access_key_id+" ");
}
private byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception{
byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
byte[] kDate = HmacSHA256(dateStamp, kSecret);
byte[] kRegion = HmacSHA256(regionName, kDate);
byte[] kService = HmacSHA256(serviceName, kRegion);
byte[] kSigning = HmacSHA256("aws4_request", kService);
return kSigning;
}
private byte[] HmacSHA256(String data, byte[] key) throws Exception {
// TODO Auto-generated method stub
String algorithm="HmacSHA256";
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
return mac.doFinal(data.getBytes("UTF8"));
}
}
Please help me.
Thanks in advance :)
[pls tell me if u require more info about my code]

Can't get a Parameter in Servlet [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
I want to upload multiple files to server and get a parameter "testname" in a JSP page . But it always return a null value.
I found the cause of error. Because of "enctype="multipart/form-data"". If I remove it from the form, I can get a parameter but I can't upload multiple files to server. How can I do both of them?
lib: http://www.java2s.com/Code/Jar/c/Downloadcosmultipartjar.htm
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input name="testname" type="text">
<input type="file" id="file" name="file1" accept="image/*" multiple="muliple" required/><br>
<input type="submit"/>
<br><br> ${requestScope.message}
</form>
</body>
</html>
UploadServlet.java
package MyPackage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import javax.servlet.*;
import javax.servlet.http.*;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;
/**
* Servlet implementation class UploadServlet
*/
#WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private String fileSavePath;
private static final String UPLOAD_DIRECTORY = "Upload";
public void init() {
fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
if (!(new File(fileSavePath)).exists()) {
(new File(fileSavePath)).mkdir(); // creates the directory if it does not exist
}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
String testname=request.getParameter("testname");
System.out.print(testname);
String resp = "";
int i = 1;
resp += "<br>Here is information about uploaded files.<br>";
try {
MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024); /* file limit size of 1GB*/
Part _part;
while ((_part = parser.readNextPart()) != null) {
if (_part.isFile()) {
FilePart fPart = (FilePart) _part; // get some info about the file
String name = fPart.getFileName();
if (name != null) {
long fileSize = fPart.writeTo(new File(fileSavePath));
resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
} else {
resp = "<br>The user did not upload a file for this part.";
}
}
}// end while
} catch (java.io.IOException ioe) {
resp = ioe.getMessage();
}
request.setAttribute("message", resp);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
}
While using enctype="multipart/form-data", you will not get your parameters by calling request.getParameter(). The parameters are a part of the stream now.
I suggest you check the question How to upload files to server using JSP/Servlet?

Out.Print method not working?

Here is my code
LoginController.java
package mvc.demo.control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
}
else
{
//This is the point where i try to print error message on jsp.
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.jsp");
rd.include(req, resp);
}
rd.forward(req, resp);
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form method="post" action="LoginController" >
UserName: <input type="text" name="username"><BR><BR>
PassWord: <input type="password" name="password"><BR><BR>
<input type="submit" />
</form>
</body>
</html>
Please check the else block of loginController class where i am trying to print error message on my jsp file currently the "out.print" method is unable to reflect on my login.jsp file.
Kindly help me to sort this issue Thanks in advance.
You can set the error message in request attribute and can fetch it in JSP
String errorMsg = "UserName or Password is invalid !";
req.setAttribute("errorMsg", errorMsg);
req.getRequestDispatcher("/login.jsp").forward(req, res);
Now on your JSP
<h2>${errorMsg}</h2> // Print wherever you need it
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
//The error was with this line
rd.forward(req, resp);
}
else
{
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.html");
rd.include(req, resp);
}
}
}
I can't see out.close() in your code. You must close the PrintWriter object in the end.
If u want to print the error message in Jsp and first Set the Error msg in request
req.setAttribute("msg","error msg configure here");
and now you can get the same in jsp by using EL Expression.
${msg}
or You can get it by using scripting language.
<%Object obj=request.getAttribute("msg");%>
Typecast the Obj into String and print by using this
<%=str%>
Note:- Recommended to use El expression.

Servlet Image Upload - Cannot get other form fields

I am having a problem with my image upload code. When I try to use request.getParameter("title") from the form, the upload doesn't succeed. But when I remove the request.getParameter("title"), it works.
In short, how can I access other form fields? I want to store their values somewhere.
Here is my form:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Upload</title>
</head>
<body>
<div>
<form action="ImageUpload" method="POST" enctype="multipart/form-data"><br>
Title:<input type="text" name="title" id="title" /><br>
Reporter:<input type="text" name="reporter" id="reporter"><br>
Image:<input type="file" name="image" id="image" /><br>
<input type="submit" value="Upload">
</form>
</div>
</body>
</html>
The Upload Servlet:
package socialnewsreloaded.upload;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.servlet.*;
/**
* Servlet implementation class ImageUpload
*/
#WebServlet("/ImageUpload")
#MultipartConfig
public class ImageUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
String title = request.getParameter("title");
response.getWriter().print(title);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iterate = upload.getItemIterator(request);
while (iterate.hasNext()) {
FileItemStream item = iterate.next();
if (item.isFormField()) {
String fieldName = item.getFieldName();
InputStream inStream = item.openStream();
byte[] b = new byte[inStream.available()];
inStream.read(b);
String value = new String(b);
//response.getWriter().print(fieldName+":"+value);
} else {
String path = "C:/uploads";
if (FileUpload.processFile(path, item)) {
response.getWriter().print(
"File Uploaded Successfully");
} else {
response.getWriter().print(
"Error Uploading File !!");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
}
FileUpload Class:
package socialnewsreloaded.upload;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
public class FileUpload {
public static boolean processFile(String path, FileItemStream stream)
throws IOException {
File file = new File(path + File.separator + "images");
if (!file.exists()) {
file.mkdir();
}
File savedFile = new File(file.getAbsolutePath() + File.separator
+ stream.getName());
try {
FileOutputStream outStream = new FileOutputStream(savedFile);
InputStream inStream = stream.openStream();
int i = 0;
byte[] b = new byte[1024];
while((i=inStream.read(b))!=-1){
outStream.write(b, 0, i);
}
outStream.flush();
outStream.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
It's the printing, not the getParameter("title"). You shouldn't produce any output until you've consumed all the input.

Categories