I want a simple image capture/upload on mobile devices. For the actual file upload, i use Apache Commons. Now I encountered the same problem as described here: Apache commons fileupload FileItemIterator hasNext() returns false, but I can't find out where the request might have been consumed before my post method.
I tested it on my development machine, when i put in any file (image or not), the iterator is simpy empty.
Here is everything I have, I marked the actual file upload code so you don't have to sift through everything.
Thanks for the help!
#WebServlet("/scanner")
public class MyServiceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int maxFileSize = 50 * 1024;
private static final int maxMemSize = 4 * 1024;
private static final String saveFolder = "/";
private final String repoFolder;
private final DiskFileItemFactory factory;
public MyServiceServlet() {
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
repoFolder = "C:\\temp";
else
repoFolder = "/tmp";
factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File(this.repoFolder));
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get");
request.getRequestDispatcher("MyService/start.html").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Post");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>MyService</title>");
out.println("</head>");
out.println("<body>");
if (!ServletFileUpload.isMultipartContent(request)) {
out.println("<p>Nothing uploaded</p>");
} else {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!FILE UPLOAD HERE
try {
FileItemIterator it = upload.getItemIterator(request);
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (!item.isFormField()) {
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
file = new File(saveFolder + fileName);
item.write(file);
System.out.println(file);
}
}
} catch (Exception e) {
e.printStackTrace();
}
this.printUserForm(out);
}
out.println("</body>");
out.println("</html>");
}
}
start.html file, I may have missed something here
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>MyService</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="input" action="/MySercice/scanner">
<input type="file" accept="image/*;capture=camera"></input>
<input type="submit" value="upload">
</form>
</body>
</html>
web.xml, if it helps. But there is nothing here, really
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>MyService</display-name>
<welcome-file-list>
<welcome-file>start.html</welcome-file>
</welcome-file-list>
</web-app>
Try with this:
if (ServletFileUpload.isMultipartContent(request)) {
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
For those who use Seam:
Following #CR7 suggestion, I could make it work by adding the below config to the components.xml
<web:multipart-filter create-temp-files="true"
max-request-size="1024000" url-pattern="*"/>
Ps: I don't know why, but for me, any other value I put in url-pattern makes the list returns empty.
Related
public class Guestbook extends CacheHttpServlet {
/**
*
*/
private static final long serialVersionUID = 1 L;
private Vector < GuestbookEntry > entries = new Vector < GuestbookEntry > ();
private long lastModified = 0; // Time last entry was added
// Display the current entries, then ask for a new entry
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
printHeader(out);
printForm(out);
printMessages(out);
printFooter(out);
}
// Add a new entry, then dispatch back to doGet()
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
handleForm(req, res);
doGet(req, res);
}
private void printHeader(PrintWriter out) throws ServletException {
out.println("<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD>");
out.println("<BODY>");
}
private void printForm(PrintWriter out) throws ServletException {
out.println("<FORM METHOD=POST action='/hello.html'>"); // posts to itself
out.println("<B>Please submit your feedback:</B><BR>");
out.println("Your name: <INPUT TYPE=TEXT NAME=name><BR>");
out.println("Your email: <INPUT TYPE=TEXT NAME=email><BR>");
out.println("Comment: <INPUT TYPE=TEXT SIZE=50 NAME=comment><BR>");
out.println("<INPUT TYPE=SUBMIT VALUE=\"Send Feedback\"><BR>");
out.println("</FORM>");
out.println("<HR>");
}
private void printMessages(PrintWriter out) throws ServletException {
String name, email, comment;
Enumeration < GuestbookEntry > e = entries.elements();
while (e.hasMoreElements()) {
GuestbookEntry entry = (GuestbookEntry) e.nextElement();
name = entry.name;
if (name == null) {
name = "Unknown user";
email = "Unknown email";
}
email = entry.email;
comment = entry.comment;
if (comment == null) comment = "No comment";
out.println("<DL>");
out.println("<DT><B>" + name + "</B> (" + email + ") says");
out.println("<DD><PRE>" + comment + "</PRE>");
out.println("</DL>");
// Sleep for half a second to simulate a slow data source
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {}
}
}
private void printFooter(PrintWriter out) throws ServletException {
out.println("</BODY>");
out.println("</HTML>");
}
private void handleForm(HttpServletRequest req,
HttpServletResponse res) {
GuestbookEntry entry = new GuestbookEntry();
entry.name = req.getParameter("name");
entry.email = req.getParameter("email");
entry.comment = req.getParameter("comment");
entries.addElement(entry);
// Make note we have a new last modified time
lastModified = System.currentTimeMillis();
}
public long getLastModified(HttpServletRequest req) {
return lastModified;
}
}
class GuestbookEntry {
public String name;
public String email;
public String comment;
}
And in the XML file i used
<web-app>
<servlet>
<servlet-name>
GuestBook
</servlet-name>
<servlet-class>
Guestbook
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
GuestBook
</servlet-name>
<url-pattern>
/hello.html
</url-pattern>
</servlet-mapping>
</web-app>
everything i used are fine but tomcat still gives me a 404 error. although i tried by different methods but still it gives me an error.
if someone will provide a solution then it would be really appreciated.
thanks in advance
we would need to create a separate html page and will write the same content as "PrintForm" method in the code. if we do so then this servlet will work perfectly. Although this servlet used for server cache, i hope it will help you in future.
thank you
I have made a application where we can upload any file which will save in our local given directory. I want to modify it, i want to add a drop down (with multiple option i.e floor, store, section) for department. i.e if we want to upload a file in 'Store' folder, we can choose 'Store' option and the file will uploaded to the 'Store' folder. Same for 'Floor' and 'Section'.
I just need any example link for that.
i have made it in liferay.
import org.apache.commons.io.FileUtils;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class UploadDirectory extends MVCPortlet {
private final static int ONE_GB = 1073741824;
private final static String baseDir = "/home/xxcompny/workspace";
private final static String fileInputName = "fileupload";
public void upload(ActionRequest request, ActionResponse response)
throws Exception {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
long sizeInBytes = uploadRequest.getSize(fileInputName);
if (uploadRequest.getSize(fileInputName) == 0) {
throw new Exception("Received file is 0 bytes!");
}
File uploadedFile = uploadRequest.getFile(fileInputName);
String sourceFileName = uploadRequest.getFileName(fileInputName);
File folder = new File(baseDir);
if (folder.getUsableSpace() < ONE_GB) {
throw new Exception("Out of disk space!");
}
File filePath = new File(folder.getAbsolutePath() + File.separator + sourceFileName);
FileUtils.copyFile(uploadedFile, filePath);
}
}
JSP is here
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%# taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<portlet:defineObjects />
<portlet:actionURL name="upload" var="uploadFileURL"></portlet:actionURL>
<aui:form action="<%= uploadFileURL %>" enctype="multipart/form-data" method="post">
<select name="folder">
<option value="store">Store</option>
<option value="floor">Floor</option>
<option value="department">Department</option>
</select>
<aui:input type="file" name="fileupload" />
<aui:button name="Save" value="Save" type="submit" />
</aui:form>
i want the file will upload in the belonging folder.
I had somewhat similar task to upload files to specified folders, so following is bit modified code as per your requirement:
public void upload(ActionRequest request, ActionResponse response)
throws Exception {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
long sizeInBytes = uploadRequest.getSize(fileInputName);
if (sizeInBytes == 0) {
throw new Exception("Received file is 0 bytes!");
}
File uploadedFile = uploadRequest.getFile(fileInputName);
String sourceFileName = uploadRequest.getFileName(fileInputName);
/* selected folder from UI */
String paramFolder = uploadRequest.getParameter("folder");
byte[] bytes = FileUtil.getBytes(uploadedFile);
if (bytes != null && bytes.length > 0) {
try {
/* Create folder if doesn't exist */
File folder = new File(baseDir + File.separator + paramFolder);
if (!folder.exists()) {
folder.mkdir();
}
/* Write file to specified location */
File newFile = new File(folder.getAbsolutePath() + File.separator + sourceFileName);
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
fileOutputStream.write(bytes, 0, bytes.length);
fileOutputStream.close();
newFile = null;
} catch (FileNotFoundException fnf) {
newFile = null;
/* log exception */
} catch (IOException io) {
newFile = null;
/* log exception */
}
}
}
You can use the below code
String user_selected_option=request.getParameter("userSel")
realPath = getServletContext().getRealPath("/files");
destinationDir = new File(realPath+"/"+user_selected_option);
// save to destinationDir
I have a method which returns a file object of an image:
public File getPhoto(entryId){...}
I call this method from my action method and set the file to a DTO File variable:
myDto.photo = getPhoto(entryId);
// where entryId refers to the name of the image file
// e.g. ent01 for ent01.gif, ent02 for ent02.gif and so on.
Now, in my JSP file I would like to display the image through a code like this:
<img src = "${myDto.photo}">
However,I realized that the myDto.photo is a file object thus has the absolute path of the file and not the URL needed for the img src in JSP.
Through searching, I understand that I can use a servlet and use something like
<img src = "${pageContext.request.contextPath}/image/ent01.gif"}.
However, I'm a little confused about this one as I wanted the filename part (ent01.gif) to vary based from the input entryId.
I hope anyone can shed light for me on this one. A lot of thanks.
You can Create a Controller Class for you to diplay the image you want.
#Controller
public class ImageReadFile{
// this is for mapping your image related path.
#RequestMapping(value="/image/*")
public void readImage(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext sc = request.getServletContext();
//here i uploaded my image in this path
// You can set any path here
String imagePath = "/home/somefolder/Workspaces/Images/";
String [] fragmentFilename = request.getServletPath().split("/");
//Check if image isn't set
if(fragmentFilename.length <= 2){
return;
}
String filename = fragmentFilename[2];
String requestedImage = "/"+filename;
if(filename == null){
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));
if(!image.exists()){
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String contentType = sc.getMimeType(image.getName());
response.reset();
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
Files.copy(image.toPath(), response.getOutputStream());
}
}
Servlet Version.
try this.
#WebServlet("/image/*")
public class ImageWriter extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = request.getServletContext();
//here i uploaded my image in this path
// You can set any path here
String imagePath = "/home/somefolder/Workspaces/Images/";
String [] fragmentFilename = request.getServletPath().split("/");
//Check if image isn't set
if(fragmentFilename.length <= 2){
return;
}
String filename = fragmentFilename[2];
String requestedImage = "/"+filename;
if(filename == null){
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));
if(!image.exists()){
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String contentType = sc.getMimeType(image.getName());
response.reset();
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
Files.copy(image.toPath(), response.getOutputStream());
}
}
this is how you gonna set display it in jsp,
<img alt="${imageFilename}" src="${pageContext.request.contextPath}/image/${imageFilename}">
Just pass the Filename to jsp then let the controller read it and display it.
hope this will help you.
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am currently working on a dynamic web application that I want the user to be able to upload multiple files at once for the application to use. I don't know how many files the user may upload at once; it could be 2 or it could 100+ files. I am new to JSP dynamic web applications and I have started with a single upload file but I am not really sure where to go from here. I've looked at few examples searching but I haven't been able to find exactly what I was looking for. This is what I have so far:
Servlet:
package Servlets;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
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;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (isMultipart)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
String abc = item.getString();
out.println("<br><br><h1>"+abc+"</h1><br><br>");
}
}
}
catch (FileUploadException e)
{
out.println(e);
}
catch (Exception e)
{
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
}
}
.JSP File:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<p><input type="file" name="dataFile" id="fileChooser" />
<input type="submit" value="Upload" multiple="multiple" /></p>
</form>
I am looking for a way to upload multiple files instead of just one and show them in a list.
Check the FileUPload Using Servlet 3.0
It has a working code for uploading Single File Using Servlet3.0 As you can see code is now much simplified . And there is no dependancy on apache Library.
just use below index.html
<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName" multiple/>
<br>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
Only change here is I have used multiple attribute for input type File
Oh... At the first glance, looks like a simple mistake. multiple is an attribute of file input, not of the submit button.
i have upload multiple files using jsp /servlet.
following is the code that i have used.
<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
on the other hand server side. use following code.
package com.abc..servlet;
import java.io.File;
---------
--------
/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.sendRedirect("../jsp/ErrorPage.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;
String path1 = filePathUpload;
String filename = null;
File path = null;
FileItem item=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String FieldName = "";
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
if (fieldname.equals("description")) {
description = item.getString();
}
}
if (!item.isFormField()) {
filename = item.getName();
path = new File(path1 + File.separator);
if (!path.exists()) {
boolean status = path.mkdirs();
}
/* START OF CODE FRO PRIVILEDGE*/
File uploadedFile = new File(path + Filename); // for copy file
item.write(uploadedFile);
}
} else {
f1 = item.getName();
}
} // END OF WHILE
response.sendRedirect("welcome.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
images.jsp
choose files:
storeimages.java servlet
public class storeimages extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String sav_dir=""; //this will be a folder inside
//directory
PrintWriter out =response.getWriter();
//if you want u can give this at run time
sav_dir="6022"; //in my case folder name is 6022
//you can alse set this at dynamic
int flag = 0;
//now set the path
//this is the path where my images are stored
//now u can see the code
String savepath="K:/imageupload"+File.separator +sav_dir;
File file = new File(savepath);
if(!file.exists()){
file.mkdir();
}
String filename="";
List<Part> fileParts = request.getParts().stream().
filter(part->"file".equals(part.getName())).collect(Collectors.
toList());
for(Part filePart: fileParts){
filename=Paths.get(filePart.getSubmittedFileName()).
getFileName().toString();
filePart.write(savepath+File.separator+filename);
flag=1;
}
if(flag==1){
out.println("success");
}
else{
out.println("try again");
}
//now save this and run the project
}
}
You only have to write multiple, because multiple is a boolean var and only defining it, it will be true to your tag. Example below:
<input type="file" name="file" id="file" multiple/>
This will let you choose multiple files at once. Good luck
This is how I did. It will dynamically add and remove the field (multiple files). Validates it and on validation calls the action method i.e the servlet and store in the DB.
** html/jsp **
.jsp file
<div class="recent-work-pic">
<form id="upload_form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input type="hidden" id="counter" value="1" >
Add
<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_0" class="upload_input"></div>
<div id="add_field_div"></div>
<button type="submit" class="btn btn-read">Submit</button>
</form>
<p>${message}</p>
</div>
jquery validation
<script>
$(document).ready(function(){
$('#add_fields').click( function(){
add_inputs()
});
$(document).on('click', '.remove_fields', function() {
$(this).closest('.record').remove();
});
function add_inputs(){
var counter = parseInt($('#counter').val());
var html = '<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_' + counter + '" class="upload_input">Remove</div>';
$('#add_field_div').append(html);
$('#counter').val( counter + 1 );
}
$('form#upload_form').on('submit', function(event) {
//Add validation rule for dynamically generated name fields
$('.upload_input').each(function() {
$(this).rules("add",
{
required: true,
messages: {
required: "File is required",
}
});
});
});
$("#upload_form").validate();
});
</script>
servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
PrintWriter writer = response.getWriter();
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("/resources/datenBank.properties"));
if (!ServletFileUpload.isMultipartContent(request)) {
writer.println("Fehler: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
String message = null;
InputStream inputStream = null;
Connection dbConnection = null;
String page = "";
try {
for (Part filePart : request.getParts()) {
System.out.println("filePart" + filePart.getName() + "-----" + filePart.getSize());
if (filePart != null && filePart.getSize() != 0) {
inputStream = filePart.getInputStream();
System.out.println("inputStream" + inputStream);
HttpSession session=request.getSession();
session.setAttribute("username",request.getRemoteUser());
Class.forName(properties.getProperty("driverClassName"));
dbConnection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
if (dbConnection != null) {
String sql = "INSERT INTO skl_lieferung (file_name, file_size, file_content,file_content_type, entry_time, user) values (?,?,?,?,?, ?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
if (inputStream != null) {
statement.setString(1, getFileName(filePart));
statement.setLong(2, filePart.getSize());
statement.setBlob(3, inputStream);
statement.setString(4, filePart.getContentType());
}
Calendar calendar = Calendar.getInstance();
java.sql.Date entryDate = new java.sql.Date(calendar.getTime().getTime());
statement.setDate(5, entryDate);
statement.setString(6, request.getRemoteUser());
//statement.setString(6, username);
int row = statement.executeUpdate();
if (row > 0) {
message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
message = "Fehler: Connection Problem";
}
} message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
page = "index.jsp";
System.out.println("cannot execute if condition");
message = "Das Upload-Feld darf nicht leer sein ";
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
return;
}
}
}catch (Exception exc) {
page = "index.jsp";
message = "Fehler: " + exc.getMessage();
exc.printStackTrace();
} finally {
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
page = "index.jsp";
request.setAttribute("message", message);
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
}
}
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
I hope people find it useful!!
To upload a single file you should use a single tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.
That is, use the below line multiple times:
<input type="file" name="dataFile" id="fileChooser" /><br><br>
Refer this link for details
I hope this helps.
I am uploading files (of different content types) using Apache fileupload API as follows:
FileItemFactory factory = getFileItemFactory(request.getContentLength());
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(maxSize);
uploader.setProgressListener(listener);
List<FileItem> uploadedItems = uploader.parseRequest(request);
... saving files to GridFS using the following method:
public String saveFile(InputStream is, String contentType) throws UnknownHostException, MongoException {
GridFSInputFile in = getFileService().createFile(is);
in.setContentType(contentType);
in.save();
ObjectId key = (ObjectId) in.getId();
return key.toStringMongod();
}
... calling saveFile() as follows:
saveFile(fileItem.getInputStream(), fileItem.getContentType())
and reading from GridFS using the following method:
public void writeFileTo(String key, HttpServletResponse resp) throws IOException {
GridFSDBFile out = getFileService().findOne(new ObjectId(key));
if (out == null) {
throw new FileNotFoundException(key);
}
resp.setContentType(out.getContentType());
out.writeTo(resp.getOutputStream());
}
My servlet code to download the file:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
String[] uriParts = uri.split("/"); // expecting "/content/[key]"
// third part should be the key
if (uriParts.length == 3) {
try {
resp.setDateHeader("Expires", System.currentTimeMillis() + (CACHE_AGE * 1000L));
resp.setHeader("Cache-Control", "max-age=" + CACHE_AGE);
resp.setCharacterEncoding("UTF-8");
fileStorageService.writeFileTo(uriParts[2], resp);
}
catch (FileNotFoundException fnfe) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
catch (IOException ioe) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
}
However; all non-ASCII characters are displayed as '?' on a web page with encoding set to UTF-8 using:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
Any help would be greatly appreciated!
Apologies for taking your time! This was my mistake. There is nothing wrong with the code or GridFS. My test file's encoding was wrong.
resp.setContentType("text/html; charset=UTF-8");
Reason: only content type, together with a binary InputStream are passed on.
public void writeFileTo(String key, HttpServletResponse resp) throws IOException {
GridFSDBFile out = getFileService().findOne(new ObjectId(key));
if (out == null) {
throw new FileNotFoundException(key);
}
resp.setContentType(out.getContentType()); // This might be a conflict
out.writeTo(resp.getOutputStream());
}