adding text input to multipart/form-data makes it fail [duplicate] - java

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
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)

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.

Related

Java-IO UTF-8 encoding problem to save html file

What I am trying to do is a blog page with jsp. For this purpose, I save the content of blogs in an html file. I am using a jsp file to update the content in the existing html file via the browser. I used the textarea tag in a jsp file to edit this html file through the browser. There is no encoding problem in the html content transferred to the textarea. But when I make changes to the html file and save it, the utf-8 characters turn out to be incorrect. For Example:
The html file is read and placed comfortably in the textarea without any encoding problems
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Üzerine Notlar</h1>
</body>
</html>
When i submit for save it:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Ãzerine Notlar</h1>
</body>
</html>
There is the classes and jsp files:
setBlog.jsp (Html file is setting in this file)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<jsp:include page="navbar.jsp"/>
<form action="adminBlogProcess?meth=update" method="post">
id:<input type="text" readonly="readonly" value="${setMe.textId}" name="tid">
<label>Text Title</label>
<input type="text" name="name" class="form-control" value="${setMe.name}"/>
<label>File Path</label>
<input type="text" name="textPath" class="form-control" value="${setMe.textPath}"/>
<label>Kategori</label>
<select class="form-control" name="selectedCategory">
<c:forEach items="${loc}" var="val">
<option value="${val.categoryId}">${val.categoryName}</option>
</c:forEach>
</select>
<label>İçerik:</label>
<textarea class="form-control" name="content" rows="100">${contentOfDoc}</textarea>
<input type="submit" class="btn btn-primary" value="Save Changes">
</form>
</body>
</html>
AdminBlogProcess.java
package Controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
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 DataAccess.CategoryDao;
import DataAccess.TextDao;
import Model.Category;
import Model.Text;
#WebServlet("/adminBlogProcess")
public class AdminBlogProcess extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7693704779591981580L;
private CategoryDao cd;
private TextDao td;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String meth = req.getParameter("meth");
String msg="";
if (meth.equalsIgnoreCase("update")) {
update(req);
msg="Yazı Güncellendi!";
} else if (meth.equalsIgnoreCase("add")) {
} else if (meth.equalsIgnoreCase("delete")) {
}
req.setAttribute("message", msg);
req.getRequestDispatcher("/admin/admin.jsp").forward(req, resp);
}
//This update method is write new content into the html file
private void update(HttpServletRequest req) {
String name=req.getParameter("name");
String textPath=req.getParameter("textPath");
int id=Integer.valueOf(req.getParameter("tid"));
Category ct=getCd().getCategoryById(Integer.valueOf(req.getParameter("selectedCategory")));
Text txt=new Text(name, textPath, ct, id);
getTd().update(txt);
String content=req.getParameter("content");
String path="C:\\Users\\90551\\Desktop\\Eclipse Projeler\\2022 Yaz-Haziran Arsiv\\JAVA SERVER PAGES\\004BlogSitesi\\src\\main\\webapp\\texts\\"+textPath;
try (FileWriter fw = new FileWriter(new File(path), StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(fw)){
bw.write("");
bw.append(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CategoryDao getCd() {
if (cd == null) {
cd = new CategoryDao();
}
return cd;
}
public void setCd(CategoryDao cd) {
this.cd = cd;
}
public TextDao getTd() {
if (td == null) {
td = new TextDao();
}
return td;
}
public void setTd(TextDao td) {
this.td = td;
}
}
What should i do for fix that encodin problem?

How do I upload JSP file content to textarea

I want to edit an jsp file from textarea in browser. So i need to upload jsp content to textarea.
For example i have a readMe.jsp file like that:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>
I want this edit like that:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>
<hr>
<h2>Read Me Second Head</h2>
<p>This is read me content 2</p>
The way I think to be able to do this in the browser is to upload the jsp content to textarea and edit it from there. Does anyone know how I can do this?
If I have a way to edit a jsp file differently from the browser, it can also be.
Thanks.
This is just an example how a JSP page can be edited from a browser.
webapp/readme.jsp is a page to edit.
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Read Me</title>
</head>
<body>
<h1>Read Me</h1>
<p> This is read me content</p>
<p>Edit this page</p>
</body>
</html>
webapp/edit/readme.jsp contains a form within that a content of a readme.jsp page can be edit.
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Edit | Read Me</title>
</head>
<body>
<h1>'Read Me' edit page</h1>
<form method="post" action="${pageContext.request.contextPath}/edit/readme">
<label>
<textarea name="newContent" cols="96" rows="16">${content}</textarea>
</label>
<br><br>
<button type="submit">Save</button>
</form>
</body>
</html>
EditReadMe.java is a servlet.
The method doGet is triggered by the Edit this page link from the webapp/readme.jsp. It read content from the webapp/readme.jsp file and passes it to the webapp/edit/readme.jsp.
The method doPost is responsible for working with the form from the webapp/edit/readme.jsp and updating content for the webapp/readme.jsp file.
package com.example.editjsp;
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.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
#WebServlet(name = "readMeEditor", value = "/edit/readme")
public class EditReadMe extends HttpServlet {
private static final String RESOURCE_PATH = "/readme.jsp";
private Path pathToFile;
#Override
public void init() {
pathToFile = Path.of(getServletContext().getRealPath(RESOURCE_PATH));
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String contentToEdit = Files.readString(pathToFile);
req.setAttribute("content", contentToEdit);
req.getRequestDispatcher("/edit/readme.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Files.writeString(pathToFile, req.getParameter("newContent"));
resp.sendRedirect(req.getContextPath() + RESOURCE_PATH);
}
}

Parsing file from local drive via JSP using commons-fileupload (empty List<FileItem>)

I am trying to parse file from local drive (Windows 10) to server running on Linux box. The servlet is less than 3.0 version so I am using the Apache FileUpload and IO jars. I have 2 problems trying to parse the file.
The submit using <input type = "submit" value = "Upload File" > currently won't submit the data so I am using <button id="ok" onclick="document.forms[0].submit();return false;">Submit</button>.
Second and more serious problem is that I am not able to upload parsed data to List. After I submit the form, the List is empty. I have commented out every method in jsp form so I should not read and parse the request body before the Apache upload (but I am no sure how to verify the body is not empty before I try to read the file). I have also tried to upload the text instead of file (to check if the there is problem trying to access windows file system) but with no success.
Maybe I am missing something obvious. Can you please give me some hints how to troubleshoot this. Thank you
JSP (old file)
<%# page language="java" %>
<%# page contentType="text/html; charset=UTF-8" %>
<%# include file="upload_function.jspf" %>
<%String pageLanguage=getLanguage(request);%>
<%# MultipartConfig%>
<%#WebServlet("/upload")%>
<html>
<head>
<link rel="stylesheet" type="text/css" href="upload.css"></link>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" ></form>
<div>
<tr>
<h4>Uploaded File:</h4>
<%=getLocalImage(request)%>
</tr>
</div>
<div>
<tr>
<label for=""><h4>File Upload:</h4></label>
<input type="file" id="image" name="image" accept="image/png, image/jpeg" >
<input type = "submit" value = "Upload File" >
</tr>
</div>
<div>
<tr>
<p>
<button id="ok" onclick="document.forms[0].submit();return false;">Submit</button>
<button id="cancel" onclick="javascript:window.close();return false;">Ok</button>
</p>
</tr>
</div>
</form>
</body>
</html>
JSPF (old file)
<%# page import="java.io.*" %>
<%# page import="java.util.*" %>
<%# page import="javax.servlet.*" %>
<%# page import="org.apache.commons.fileupload.disk.*" %>
<%# page import="org.apache.commons.fileupload.servlet.*" %>
<%# page import="org.apache.commons.fileupload.*" %>
<%# page import="org.apache.commons.io.*" %>
<%!
public String getLocalImage(HttpServletRequest request) throws ServletException, IOException
{
String result = "null";
String UPLOAD_DIRECTORY = "/final/directory/for/file/upload/";
// Check the content
if(ServletFileUpload.isMultipartContent(request)){
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setSizeThreshold(40960);
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(2000000);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
}
catch(Exception ex){
ex.printStackTrace();
}
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
File uploadedFile = new File(UPLOAD_DIRECTORY,"picture.png");
// List<FileItem> items is empty - error trying to use the iterator
FileItem item = iter.next();
item.write(uploadedFile);
result = "file upload successful";
}
catch (Exception t) {
t.printStackTrace();
return result;
}
return result;
}
else {
return "not multipart";
}
}
%>
Edit:
So I think main problem was, I did not connect the jsp file with the servlet through the action attribute in the form.
I have created the functional example of the upload servlet but I would need to import the UploadServlet class into JSP file without actually using the .java project file.
I have created the jar file of the UploadServlet class and add the jar file into the WEB-INF/lib folder of the web app. But when I try to create the instance of the UploadServlet class, IDE tells me it can't be resolved to the type.
Is it possible to import the user defined class into JSP like this? Do I e.g. need some more dependencies? I am not sure what about the tomcat servlet-api.jar, the UploadServlet jar is probably trying to use it but the servlet-api classes are outside of the web app. Hovewer it is not possible to include the servlet-api.jar directly under the WEB-INF/lib web app.
UploadServlet.java ---> UploadServlet.jar
package test.pkg;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
// constructor
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// doPost implementation
}
}
JSP with UploadServlet
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="test.pkg.UploadServlet" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload: <input type="file" name="uploadFile" />
<input type="submit" value="Upload" />
<%
UploadServlet servletUp = new UploadServlet();
servletUp.doPost(request, response);
%>
</form>
</body>
</html>
I'm answering with your previous commentary in mind where you asked if the Servlet could be defined in a JSP, as you were not sure you would have access to Java classes in this project.
You can, as you have access to the request and response inside any JSP, like any other servlet (JSP is a servlet). That said, you should separate the form from the handling of its values. A generally good pattern to use is POST-REDIRECT-GET.
I'm using JSTL for the form as this is better practice.
To handle the request in another JSP, I'm forced to resort to scriptlets, which is usually a sign of bad design, but considering you can't edit Java source, no other choice...
Page containing form: fileUploadForm.jsp
Set your form to POST to another page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My upload file test form</title>
</head>
<body>
<h1>My upload file test form</h1>
<!-- Display messages -->
<div class="messages">
<c:if test="${not empty sessionScope.uploadErrors}">
<c:forEach items="${sessionScope.uploadErrors}" var="err">
<p class="error"><c:out value="${err}" /></p>
</c:forEach>
</c:if>
<c:if test="${not empty sessionScope.uploadSuccess}">
<p class="success">File uploaded successfully: <c:out value="${sessionScope.uploadSuccess}" /></p>
</c:if>
</div>
<!-- Form with POST action pointing to uploadFormAction.jsp -->
<form name="upload-test" action="./uploadFormAction.jsp" method="POST" enctype="multipart/form-data">
<label for="upload">Upload file:</label>
<input type="file" name="uploaded" id="upload" accept="image/png" />
<div class="submits">
<input type="submit" value="Send" />
</div>
</form>
</body>
</html>
JSP with data handling code: fileUploadAction.jsp
Handle the POST request, record the result (errors or success), and then redirect back to your form to show them
<%#page import="org.apache.commons.fileupload.FileItem"%>
<%#page import="java.io.File"%>
<%#page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//Storage for error messages
List<String> errors = new ArrayList<>();
session.setAttribute("uploadErrors", errors);
session.setAttribute("uploadSuccess", null);
//Check for correct form encoding
if (!"POST".equalsIgnoreCase(request.getMethod())) {
errors.add("Form must have method=\"POST\"");
}
if (!ServletFileUpload.isMultipartContent(request)) {
errors.add("Form has no multipart data to read from");
}
if (errors.size() < 1) {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4L * 1024 * 1024);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
String found = null;
for (FileItem item : items) {
if (item.isFormField()) {
//Process other fields in form
} else if ("uploaded".equals(item.getFieldName())) {
if (item.getSize() > 0) {
if (found != null) {
errors.add("Only one file allowed");
} else {
found = item.getName();
File uploadedFile = new File("./uploads/","picture.png");
if (uploadedFile.exists()) uploadedFile.delete();
item.write(uploadedFile);
}
}
} else { //Other file field
//Ignore it ? error ?
}
}
if (found == null) {
errors.add("No uploaded file !");
}
session.setAttribute("uploadSuccess", found);
} catch (Exception e) {
e.printStackTrace();
//Should log it and return it in a more readable form
errors.add(e.getMessage());
}
}
response.sendRedirect("uploadFormPage.jsp");
%>
Now considering your question edits, if you have your Servlet class already defined and want to call it from a JSP, then I suppose you could use the same principles as described here, and create a new intance of the servlet to call its doPost Method where you get the POST request, but that's supposing your servlet is stateless and doesn't use init parameters from web.xml...
How you should do it if you can write a Servlet
Keep the same form code, just change the destination of your <form> to action="<c:url value ="/uploadFile" />"
Create your Servlet with url pattern set to "/uploadFile" to handle the POST (e.g. using #WebServlet annotation), and same code as fileUploadAction.jsp
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet("/uploadFile")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//Storage for error messages
List<String> errors = new ArrayList<>();
session.setAttribute("uploadErrors", errors);
session.setAttribute("uploadSuccess", null);
//Check for correct form encoding
if (!"POST".equalsIgnoreCase(request.getMethod())) {
errors.add("Form must have method=\"POST\"");
}
if (!ServletFileUpload.isMultipartContent(request)) {
errors.add("Form has no multipart data to read from");
}
if (errors.size() < 1) {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4L * 1024 * 1024);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
String found = null;
for (FileItem item : items) {
if (item.isFormField()) {
//Process other fields in form
} else if ("uploaded".equals(item.getFieldName())) {
if (item.getSize() > 0) {
if (found != null) {
errors.add("Only one file allowed");
} else {
found = item.getName();
File uploadedFile = new File("./uploads/","picture.png");
if (uploadedFile.exists()) uploadedFile.delete();
item.write(uploadedFile);
}
}
} else { //Other file field
//Ignore it ? error ?
}
}
if (found == null) {
errors.add("No uploaded file !");
}
session.setAttribute("uploadSuccess", found);
} catch (Exception e) {
e.printStackTrace();
//Should log it and return it in a more readable form
errors.add(e.getMessage());
}
}
response.sendRedirect("uploadFormPage.jsp");
}
}

Display image on JSP page using mySql [duplicate]

This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 5 years ago.
Please help me in displaying image in a particular section on a JSP page which is stored in mySql database and also tell me that can we store image in any datatype?
Web pages display images from URLs.
You can either encode the image in a data: URI, or write server-side code to serve it in response to some URL.
add this servlet to your project like this :
package com.app.meservlets;
import java.io.IOException;
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 com.app.upload.UploadPicture;
/**
*
* #author user-sqli date: 12/05/2016 17:42
*/
#WebServlet(urlPatterns = "/upload", loadOnStartup = 1)
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
// 50MB
public class ControllerUploadPicture extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String appPath = request.getServletContext().getRealPath("");
Part part = request.getPart("file");
UploadPicture.createNewInstance().TranseferPicture(part, appPath);
getServletContext().getRequestDispatcher("/show.jsp").forward(request,
response);
}
}
and add this classto your project :
package com.app.upload;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Part;
/**
*
* #author user-sqli date: 12/05/2016 17:30
*/
public class UploadPicture {
private static final String EXTENSION = ".";
public static final String SAVE_DIR = "uploadImage";
private static UploadPicture uploadPicture = null;
private static final Logger LOGGER = Logger.getLogger(UploadPicture.class
.getName());
private UploadPicture() {
}
public String TranseferPicture(Part part, String appPath) {
String savePath = appPath + File.separator + SAVE_DIR;
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String nameImage = fileName + EXTENSION + getExtensionImage(part);
try {
part.write(savePath + File.separator + nameImage);
LOGGER.log(Level.FINE, "Upload Picture to {0} ", savePath
+ File.separator + nameImage);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.toString(), ex);
}
return nameImage;
}
private String getExtensionImage(Part part) {
return part.getContentType().split("/")[1];
}
public static UploadPicture createNewInstance() {
if (uploadPicture == null) {
uploadPicture = new UploadPicture();
}
return uploadPicture;
}
}
in your jsp like this :
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload file</title>
</head>
<body>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file" /><br /> <input type="submit"
value="Upload" />
</form>
</body>
</html>
and for shoing this image :
<%# 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 >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
uploaded image sucess.
<%-- <img width="100px" height="100px" src="<c:url value="/uploadImage/${name}" />"> --%>
</body>
</html>
this example require servlet >=3.1

How to print Hindi text into web page by giving servlet , java and html code

i am using servlet, java and one html code to extract hindi text from following URL : https://hi.wikipedia.org/wiki/%E0%A4%B5%E0%A4%BE%E0%A4%B0%E0%A4%BE%E0%A4%A3%E0%A4%B8%E0%A5%80
i want to display hindi font by servlet code , code is given as :
//Extraction1.java //java file
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class Extraction1 {
public String toHtmlString(String url) throws IOException
{
StringBuilder sb = new StringBuilder();
for(Scanner sc = new Scanner(new URL(url).openStream()); sc.hasNext(); )
sb.append(sc.nextLine()).append('\n');
return sb.toString();
}
}
MultiParamServlet3.java // servlet file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MultiParamServlet3 extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
resp.setContentType("text/html");
String[] values=req.getParameterValues("habits");
Extraction1 t=new Extraction1();
String s=t.toHtmlString(values[0]).replaceAll("\\<.*?>","");
pw.println("<html><head><meta charset=\"utf-8\"></head><body>"+s+"</body></html>");
pw.close();
}
}
index.html // html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form method="Post" action="MultiParamServlet3">
<Label> <br><br> &n bsp; Enter the URL : </label>
<input name='habits' id='t2'>
<input type="submit" name="submit">
</form>
</body>
</html>
servlet program able to print english text after extraction, but hindi text converted as ????? (question mark).
how to print hindi text into web page by servlet program ?
You have to set encoding response.
change "text/html" to "UTF-8".
resp.setCharacterEncoding("UTF-8");
Use StringEscapeUtils class from apache.commons.lang and implement it like:
String output=StringEscapeUtils.unescapeHtml3(responseMessageString);
mathod depends on api version i am using commons.lang 3.3.

Categories

Resources