This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 5 years ago.
I am trying to upload a file through my web application and read the uploaded file. First I can upload it to my desktop. But this is not what I want. I want to create a directory named file (you can see in picture) inside my project explorer in Eclipse. And then upload the file to there. I tried many ways to give the path but it always giving me this exception : File Upload Failed due to java.io.FileNotFoundException.Here is my project explorer.enter image description here
https://ibb.co/niTaN6 here is the image
And here is my code.
package com.fileupload;
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;
#WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "/GraphCoverage/file/";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// process only if its multipart content
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<FileItem> multiparts = upload.parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
// File uploaded successfully
request.setAttribute("message", "Your file has been uploaded!");
}
catch (Exception e)
{
request.setAttribute("message", "File Upload Failed due to " + e);
}
} else
{
request.setAttribute("message", "This Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Hi chalesea23 you need to provide full system path like "C:/Users/abc/eclipse-workspace/Test/file", then it will work. Because a folder in your eclipse is nothing but a folder on your PC.
Below is working for me.
package com.java;
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;
#WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "C:/Users/abc/eclipse-workspace/Test/file";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// process only if its multipart content
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<FileItem> multiparts = upload.parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
// File uploaded successfully
request.setAttribute("message", "Your file has been uploaded!");
} catch (Exception e) {
request.setAttribute("message", "File Upload Failed due to " + e);
}
} else {
request.setAttribute("message", "This Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Related
I am trying to download a file from my web application in an ActionForward java class. I have looked at many examples to try different solutions but none have worked so far. My knowledge is limited and have spent a good amount of time to get this to work.
From my jsp page a link hits an action in my struts config which takes the thread to an ActionForward return type method on a java class.
I then take the passed in file name and grab it from an amazon s3 bucket. With the file downloaded from the s3 bucket I now have the file bytes[].
I need to then have the file download to the local machine as most files do (appearing in the downloads folder and the web showing the download at the bottom bar of the page)
After following some examples I kept getting this error
Servlet Exception - getOutputStream() has already been called for this
response
I got past the error by doing
response.getOutputStream().write
Instead of creating a new OutputStream like this
OutputStream out = response.getOutputStream();
Now it runs without errors but no file gets downloaded.
Here is the java file I am attempting to do this in.
As you can see in the file below is a commented out DownloadServlet class which I tried as another attempt. I did this because a lot of the examples have classes the extends HttpServlet which I made DownloadServlet extend but it made no difference.
package com.tc.fms.actions;
import com.sun.media.jai.util.PropertyUtil;
import com.tc.fw.User;
import org.apache.commons.beanutils.PropertyUtils;
import java.io.*;
import java.io.File;
import java.util.ArrayList;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tc.fw.actions.BaseAction;
import org.apache.struts.upload.FormFile;
import io.isfs.utils.ObjectUtils;
import com.tc.fw.*;
import com.tc.fms.*;
import com.tc.fms.service.*;
public class FileDownloadAction extends BaseAction {
private static ObjectUtils objectUtils = new ObjectUtils();
private final int ARBITARY_SIZE = 1048;
public ActionForward performWork(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("In File Download Action");
ActionMessages errors = new ActionMessages();
User user = (User)request.getSession().getAttribute(User.lookupKey);
String fileName = (String) PropertyUtils.getSimpleProperty(form, "fileName");
String outboundDir = (String) PropertyUtils.getSimpleProperty(form, "outboundDir");
System.out.println("File Dir: " + outboundDir + " File Name: " + fileName);
try{
try {
// Get file from amazon
byte[] fileBytes = objectUtils.getFileDavid(outboundDir, fileName);
if (fileBytes != null) {
java.io.File file = File.createTempFile(fileName.substring(0, fileName.lastIndexOf(".") - 1), fileName.substring(fileName.lastIndexOf(".")));
FileOutputStream fileOuputStream = new FileOutputStream(file);
fileOuputStream.write(fileBytes);
try {
/* DownloadServlet downloadServlet = new DownloadServlet();
downloadServlet.doGet(request, response, file);*/
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
InputStream in = new FileInputStream(file);
/*OutputStream out = response.getOutputStream();*/
byte[] buffer = new byte[ARBITARY_SIZE];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
response.getOutputStream().write(buffer, 0, numBytesRead);
}
} catch (Exception e) {
System.out.println("OutputStream EROOR: " + e);
}
} else {
System.out.println("File Bytes Are Null");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.no.file.found"));
saveErrors(request, errors);
return mapping.findForward("failure");
// Failed
}
} catch (Exception eee){
System.out.println("Failed in AWS ERROR: " + eee);
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.failed"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
}catch (Exception ee){
System.out.println("Failed in global try");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.failed"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
return mapping.findForward("success");
}
}
I'm new in Amazon s3 web service and need to develop a command line application to transfer a file between Amazon S3 buckets. The content of the input file must be converted to the target format and then copied to the destination folder. Target format can be XML or Json and file content respects a given data model.
I have intermediate experience with Java and just created an account which is still pending and hence, trying to develop a workflow to solve the problem.
Well, it's not that hard. I have done it to a customer few months back, and you may find the code below. To read a file from AmazonS3 bucket go through this Amazon documentation [1]. To write a file into Amazon s3 bucket read this documentation [2].
Other than that you may need to add all the access tokens into your local Operating system. You may get some help from an Admin person to do that. Getting the correct credentials is the only tricky part as I remember.
Amazon has a nice little documentation and I recommend you to go through that too.
package org.saig.watermark.demo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.AmazonClientException;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
public class AmazonS3Util {
private static AWSCredentials credentials = null;
private static final String fileSeparator = "/";
private static final Log log = LogFactory.getLog(AmazonS3Util.class);
static {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. "
+ "Please make sure that your credentials file is at the correct "
+ "location (~/.aws/credentials), and is in valid format.",
e);
}
}
public static void readFileFromS3cketBucket(String bucketName, String key, String dirPath,
String fileName) {
FilterInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
// Remove the file if it already exists.
if (new File(dirPath + WatermarkConstants.fileSeparator + fileName).exists()) {
FileUtil.delete(new File(dirPath + WatermarkConstants.fileSeparator + fileName));
}
AmazonS3 s3 = new AmazonS3Client(credentials);
Region usEast1 = Region.getRegion(Regions.US_EAST_1);
s3.setRegion(usEast1);
log.info("Downloading an object from the S3 bucket.");
S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
log.info("Content-Type: " + object.getObjectMetadata().getContentType());
inputStream = object.getObjectContent();
File dirForOrder = new File(dirPath);
if (!dirForOrder.exists()) {
dirForOrder.mkdir();
}
outputStream = new FileOutputStream(new File(dirPath + fileSeparator + fileName));
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
public static void uploadFileToS3Bucket(String bucketName, String key, String dirPath,
String fileName) {
AmazonS3 s3 = new AmazonS3Client(credentials);
Region usEast1 = Region.getRegion(Regions.US_EAST_1);
s3.setRegion(usEast1);
s3.putObject(new PutObjectRequest(bucketName, key, new File(dirPath + fileSeparator +
fileName)));
try {
FileUtil.delete(new File(dirPath));
} catch (IOException e) {
log.error(e);
}
}
public static void main(String[] args) {
readFileFromS3cketBucket("bucketName",
"s3Key",
"localFileSystemPath",
"destinationFileName.pdf");
}
}
Hope this helps. Happy Coding !
[1] http://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingJava.html
[2] http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpJava.html
So I'm currently programming a java ee Backend, where I can store pictures or videos and I want to somehow stream the video from the backend to a client(internet browser) with the help of html5 < video> tag.The video part is not working it's just giving me a blackscreen,when I play the video, but the audio is playing. Image part is working well.
import com.dispway.restserver.facade.PlaylistEntryFacade;
import com.dispway.restserver.smallModel.SmallPlaylistEntry;
import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
#WebServlet("entry")
public class PlaylistEntryServlet extends HttpServlet {
#EJB
PlaylistEntryFacade playlistEntryFacade;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//entry-id
String e_id = req.getParameter("e_id");
//entry-type
String type = req.getParameter("type");
SmallPlaylistEntry entry = playlistEntryFacade.findById(Integer.parseInt(e_id));
ServletContext context = getServletContext();
String mimeType;
ServletOutputStream outputStream;
switch (type) {
case "1":
System.out.println("image-type");
mimeType = context.getMimeType(entry.getFilename());
if (mimeType == null) {
mimeType = "image/png";
}
resp.setContentType(mimeType);
outputStream = resp.getOutputStream();
outputStream.write(entry.getFile());
outputStream.close();
break;
case "2":
// NOT WORKING, I only get BlackScreen
System.out.println("video-type");
System.out.println(entry.getFilename());
mimeType = context.getMimeType(entry.getFilename());
if (mimeType == null) {
System.out.println("mime is null");
mimeType = "video/mp4";
}
System.out.println("MimeType: " + mimeType);
resp.setContentType(mimeType);
resp.setContentLength(entry.getFile().length);
//getFile returns a byte[]
BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(entry.getFile()));
byte[] content = new byte[4096];
int bytesRead;
outputStream = resp.getOutputStream();
while ((bytesRead = bufferedInputStream.read(content)) != -1) {
outputStream.write(content, 0, bytesRead);
}
bufferedInputStream.close();
outputStream.close();
break;
}
}
}
Sorry the video has the wrong codec, So the html <video> wasn't showing the video.
I want to resize the image by giving pixels explicitly from out side.Here I am able to compress the image by hard coding by specifying compression quality.
I need to resize by explicit height and width too
Here I compressed the image by using this code:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ImageServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File f = new File("D:\\Compress");
File f1 = new File("D:\\Original");
if (!f.exists()) {
f.mkdir();
}
if (!f1.exists()) {
f1.mkdir();
}
String p = req.getParameter("myfile");
String actualPath = "D:/Original/" + p;
/*
* System.out.println(p); File file = new File(p); String s=
* file.getCanonicalPath(); System.out.println(s);
*/
File imageFile = new File(actualPath);
File compressedImageFile = new File("D://Compress/compressed_" + p + ".jpg");
InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);
float quality = 0.3f;
// create a BufferedImage as the result of decoding the supplied
// InputStream
//reads image
BufferedImage image = ImageIO.read(is);
// get all image writers for JPG format
Iterator writers = (Iterator) ImageIO.getImageWritersByFormatName("jpg");
// checks the format
java.util.Iterator<ImageWriter> iterator = (java.util.Iterator<ImageWriter>) writers;
if (!iterator.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) ((java.util.Iterator<ImageWriter>) writers).next();
//sends to output stream
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
// compress to a given quality
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
// appends a complete image stream containing a single image and
// associated stream and image metadata and thumbnails to the output
writer.write(null, new IIOImage(image, null, null), param);
// close all streams
is.close();
os.close();
ios.close();
writer.dispose();
// redirect to success page
resp.sendRedirect("./Success.html");
}
}
So code this working fine but its only resizing (means converting 43kb image file to 23kb) the image size.
Here I want to change the hieght and width of image.
Thanks in advance.
I am usning the following code to upload a servlet. However it is repeatedly throwing an error..
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\tmp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
System.out.println("hello ");
try{
// Parse the request to get file items.
System.out.println("hello ");
List<FileItem> fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println("brilliant ");
}
}
}
however the error i am getting is
SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
its also not going to expception block:(
I tried printing the stacktrace..didn't work..as for configuration is concerned i believe its fine..i gace sysout statements inside the dopost method it printed fine..to the point where i have delcared LIST..after that its going ahead
The error appears to be happening before even calling your servlet. It's probably a configuration issue.