Can't get a Parameter in Servlet [duplicate] - java

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?

Related

not able to use jquery ajax FormData with servlet

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.

How to write to a file in Java using Servlet [duplicate]

This question already has answers here:
How to save generated file temporarily in servlet based web application
(2 answers)
Closed 5 years ago.
I am creating a Java Web Application which takes data from a HTML form and saves it to a text file using a Servlet. However when I run the application I cannot see the text file anywhere so I am unsure if it was created successfully or not. Does anyone have any ideas why the file is not appearing?
Here is my code for the HTML form:
<html>
<head>
<title>Register Customer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name = "regcustomer" method = "get" action = "CustomerServlet" >
Customer Name
<input type="text" name="customerName"> <br>
Customer Address
<input type="text" name="customerAddress"> <br>
Telephone Number
<input type="text" name="telNo"> <br>
Email
<input type="text" name="email"> <br>
Cost per KG shipped
<input type="text" name="costPKG"> <br>
<input type="submit" value="Register"> <br> <br>
Back
</form>
</body>
And here is my code for the servlet:
package Servlets;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomerServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
String customerName;
customerName = request.getParameter("customerName");
String customerAddress = request.getParameter("customerAddress");
String telNo;
telNo = request.getParameter("telNo");
String email = request.getParameter("email");
String costPKG = request.getParameter("costPKG");
try{
File file = new File("C:/xyz.txt");
FileWriter fstream = new FileWriter(file,true);
try (BufferedWriter out = new BufferedWriter(fstream)) {
out.write(customerName+" "+customerAddress+" "+telNo+" "+email+"
"+costPKG);
out.newLine();
}
pw.println("File is created successfully");
}
catch (IOException e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any suggestions would be much appreciated
Try adding the line:
#WebServlet(urlPatterns = { "/CustomerServlet" })
before:
public class CustomerServlet extends HttpServlet {
Note: If you are using old container (not implemented Servlet 3.0, like Tomcat 6.0), then you have to edit web.xml.

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

Jsp doesn't show swf File

I have a Webproject with JavaEE (Tomcat, Jsp, Servlets)
I want to Show a SWF in my Jsp Page (game.jsp). For doing this i Need a Servlet, which is this:
package src;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
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 util.SystemEnviroement;
/**
* Servlet implementation class ImageServlet
*/
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ImageServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletContext();
String imageName = request.getParameter("imageName");
SystemEnviroement env = new SystemEnviroement();
String filename = env.gameFolder + "/" + imageName;
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
// sc.log("Could not get MIME type of " + filename);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
response.setContentType(mimeType);
// Set content size
File file = new File(filename);
response.setContentLength((int) file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
}
My game.jsp is this:
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%# page import="util.*"%>
<%# page import="constants.*"%>
<%# page import="java.io.IOException"%>
<!DOCTYPE html>
<html >
<head>
<jsp:include page='header.jsp'/>
<%
String gamename = (String) request.getAttribute("javax.servlet.forward.request_uri");
int index_name = gamename.lastIndexOf("/");
gamename = gamename.substring(index_name+1,gamename.length());
%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body style="background-color:#630592;
background-repeat:no-repeat;"
>
<div class="body">
<%
try {
//SystemEnviroment wird im Konstruktor gesetzt
SystemEnviroement en = new SystemEnviroement();
String datei = en.imageViewPath + gamename +".swf";
%>
<div class=gameswf>
<a> <embed src='<%=datei %>' > </embed> </a>
</div>
<%
}catch(IOException e){
e.printStackTrace();
}
%>
</div>
</body>
</html>
So i have debugged my Project, all thinks Looks well. But after calling the Servlet, the game.jsp doesn't Show the SWF File.
The htmltext(sourcecode) also Looks well, but the game.jsp doesn't Show the SWF File:
<div class=gameswf>
<a> <embed src='http://localhost:8080/Game/imageView?imageName=3-pandas.swf'> </embed> </a>
</div>
If i call this URL in my running web Project "http://localhost:8080/Game/imageView?imageName=3-pandas.swf", i can sell the SWF File and all is fine.
Do you have any idea why the jsp page doesn't Show my SWF File. If i go to the Internet explorer add ons, i can also see that Shockwave Flash Object is loading.
Thanks for helping !
This is the Image from ie 11 network monitoring feature from developer Tools:
I suggest you to create an html file (with html extension) and write the code you expect from the jsp to generate.
Once you make the swf work in html file, it will be a piece of cake to develop the proper jsp code in order to generate that html file.

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