I want to copy the contents of an uploaded file to a text file on my local.
The important thing is- I already have a file on my system named "Data" and I want to append the contents of uploaded file in "Data".
I have successfully copied the contents of the uploaded file but facing issue in appending the data.
Below is my Servlet file:
package pack;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
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 FileUploadHandler extends HttpServlet {
private final String UPLOAD_DIRECTORY = "D:/Data Repository.txt";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
item.write(new File(UPLOAD_DIRECTORY));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex)
{
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Can something be added or modified in the below statement so that it would append the data to the existing file rather than creating a new file every time and copying its content?
item.write(new File(UPLOAD_DIRECTORY));
Related
edit: solved below
So I need to create a server that can be used to upload files to and then serve those files back upon request. After some research it seemed like using HttpClient on the client side and FileUpload on the server side with a Tomcat servlet would be a good way to accomplish this task. After pulling from various example sources I have come up with the following code for the client:
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
public class Client {
static String url = "http://localhost:8080";
public static void main(String[] args) throws Exception {
File file = new File("2048.zip");
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody);
HttpEntity entity = builder.build();
HttpPost request = new HttpPost(url);
request.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
try {
client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
//list_files();
}
}
And this for the servlet code:
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;
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 java.io.IOException;
import java.util.Iterator;
import java.util.List;
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
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);
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This in the web-xml:
<servlet>
<servlet-name>fileservlet</servlet-name>
<servlet-class>servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileservlet</servlet-name>
<url-pattern>/fileservlet</url-pattern>
</servlet-mapping>
When I try to run the client I just get hit with these errors until it times out.
Dec 04, 2017 4:08:34 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.net.SocketException) caught when processing request to {}->http://localhost:8080: Connection reset by peer: socket write error
Dec 04, 2017 4:08:34 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {}->http://localhost:8080
This is my first time working with servlets and Tomcat so I'm unsure if there's a configuration issue in eclipse or an actual issue with the code.
Edit: Okay so for the first time I've managed to get the file to send through the client and be saved by the server. The first thing I had to do was ensure that the "url" matched the correct servlet extension. When I launched the servlet in eclipse it automatically opened http://localhost:8080/FileServlet/FileServlet so this is what I used in the client when sending the file. I also uncommented a part of the servers.xml file having to do with thread pool.
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
Also I used the code straight from the HttpClient example page for multipart sending.
I have to store an image for a few minutes after user upload it to show a preview, before confirmation, after confirmation i need get it back and persist.
I would like to know the best pratice to do this.
I saw about Cache and Caffeine, but i don't know if this is the best pratice and how store in Cache with a random hash to get it back after
[EDIT]
Maybe I was overestimating the problem
Following the #Robert suggestion i'll use temporary files, but i still need some way to garantee that files will be deleted. So i created a new question and i'll keep this to help others that do search with these terms.
Follow the link
How guarantee the file will be deleted after automatically some time?
I do this in one of my apps.
In the upload POST, I save the image to a temporary file and then store the temporary file name in a session attribute. I use the session attribute because the image being previewed shouldn't be visible to any other users until it has been written to persistent storage.
In the subsequent GET, I pull the temporary file name out of the session and stream it out to the response, deleting it when finished. I don't bother keeping the file after the preview is rendered as I don't need it anymore.
See the full implementation below:
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
#RestController
#RequestMapping("/api/imagePreview")
public class ImagePreviewController
{
#PostMapping
public ResponseEntity<?> post(HttpSession session, #RequestPart MultipartFile file) throws IOException
{
if (file.getContentType() != null && file.getContentType().startsWith("image/")) {
Path tempFile = Files.createTempFile("", file.getOriginalFilename());
file.transferTo(tempFile.toFile());
session.setAttribute("previewImage", tempFile.toFile().getPath());
session.setAttribute("previewImageContentType", file.getContentType());
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).build();
}
}
#GetMapping
public void get(HttpServletRequest request, HttpServletResponse response) throws IOException
{
HttpSession session = request.getSession(false);
if (session == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String path = (String) session.getAttribute("previewImage");
String contentType = (String) session.getAttribute("previewImageContentType");
if (path == null || contentType == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType(contentType);
try (OutputStream out = response.getOutputStream()) {
Files.copy(Paths.get(path), out);
} finally {
Files.deleteIfExists(Paths.get(path));
}
}
}
I want to upload my excel sheet in my local system using servlet API but i am getting exception
java.io.FileNotFoundException: D:\Core-Java_Eclipse.metadata.plugins
\org.eclipse.wst.server.core\tmp0\wtpwebapps\UploadMenu\uploaded (Access is denied)
here i am using two jar 1. commons-fileupload-1.2.1.jar 2. commons-io-1.4.jar
i dont want to use third party implementation jar
Please see my code which is written in servlet
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
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.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String ctxPath=request.getRealPath("/");
File dir=new File(ctxPath,"uploaded");
if(!dir.exists()){
dir.mkdir();
}
Writer out=response.getWriter();
boolean uploadData=ServletFileUpload.isMultipartContent(request);
if(uploadData){
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024*10);
factory.setRepository(new File("c:\\temp"));
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setSizeMax(1024*1024*50);
try{
List<FileItem> fileItems=upload.parseRequest(request);
Iterator<FileItem> i=fileItems.iterator();
while(i.hasNext()){
FileItem fi=i.next();
if(!fi.isFormField()){
String fieldName=fi.getFieldName();
String fileName=fi.getName();
String contentType=fi.getContentType();
boolean isInMemory=fi.isInMemory();
long sizeInByte=fi.getSize();
StringTokenizer tok=new
StringTokenizer(fileName,"/");
String fileToWrite="";
while(tok.hasMoreTokens()){
fileToWrite=tok.nextToken();
}
File file=new File(dir,fileToWrite);
fi.write(file);
}
}
}catch(Exception e){
e.printStackTrace();
}
out.write("<h1>File Uploaded in <br/>"+dir.getAbsolutePath());
}else{
out.write("No File Uploaded");
}
}
}
please tell me how to resolve my problem and how to upload this file is user
define directry means (D:// menu) folder
thanx is Advance
For my use, I created a PDF file using flying-saucer library. It was a legacy HTML so I cleaned out the XHTML using HTMLCleaner library.
After this I serialize the XML as string then pass it to the iText module of flying-saucer to render it and subsequently create the PDF.
This PDF I place it in the OutputStream. After the response is committed I get a dialog asking to save or open it. However it does not get saved as PDF file. I have to right-click and open it in Adobe or any PDF reader.
How do I make it display in the PDF reader. And make the file be saved as .pdf file. What would be an effective and user-friendly way to handle this issue? Help as always will be greatly appreciated!
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.PrettyXmlSerializer;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XmlSerializer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;
public class MyPDF extends HttpServlet {
public MyPDF() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/pdf");
String html = request.getParameter("source");
try
{
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
TagNode node = cleaner.clean(html);
//String content = "<" + node.getName() + ">" + cleaner.getInnerHtml(node) + "</" + node.getName() + ">";
//System.out.println("content " +content);
OutputStream os = response.getOutputStream();
System.out.println("encoding " +response.getCharacterEncoding());
final XmlSerializer xmlSerializer = new PrettyXmlSerializer(props);
final String html1 = xmlSerializer.getAsString(node);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html1);
renderer.layout();
renderer.createPDF(os);
os.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void init() throws ServletException {
}
}
Your MIME type is incorrect for PDF. It should be application/pdf.
Change
response.setContentType("text/pdf");
to
response.setContentType("application/pdf");
See https://www.rfc-editor.org/rfc/rfc3778 for the RFC for the PDF MIME type.
Edit: Totally overlooked the "Save as .pdf" question.
You'll also need to add something like:
response.setHeader("content-disposition", "attachment; filename=yourFileName.pdf");
to tell the browser what the default file name should be.
I have a servlet in which I first download a pdf in from http://www.cbwe.gov.in/htmleditor1/pdf/sample.pdf upload it's content on my blobstore and when a user sends a get request in browser a blob will be downloaded in browser, but instead of downloading it's showing data in some other format. Here is my code of servlet:
package org.ritesh;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import javax.servlet.http.*;
import org.apache.commons.io.IOUtils;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileWriteChannel;
#SuppressWarnings("serial")
public class BlobURLServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
FileService fileService = FileServiceFactory.getFileService();
// Create a new Blob file with mime-type "text/plain"
String url="http://www.cbwe.gov.in/htmleditor1/pdf/sample.pdf";
URL url1=new URL(url);
HttpURLConnection conn=(HttpURLConnection) url1.openConnection();
String content_type=conn.getContentType();
InputStream stream =conn.getInputStream();
AppEngineFile file = fileService.createNewBlobFile("application/pdf");
file=new AppEngineFile(file.getFullPath());
Boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
// This time we write to the channel directly
String s1="";
String s2="";
byte[] bytes = IOUtils.toByteArray(stream);
writeChannel.write(ByteBuffer.wrap(bytes));
writeChannel.closeFinally();
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
blobStoreService.serve(blobKey, resp);
}
}
I deploy this servlet on onemoredemo1.appspot.com. Please open this url and notice when u click on BlobURL servlet it's showing content instead of showing downloading dialog. What modification should I do in my code so it shows download dialog in browser?
Look here:
resp.setContentType("text/plain");
You've said that the content is plain text, when it's not. You need to set the Content-Disposition header appropriately as an attachment, and set the content type to application/pdf.
Additionally, if you're going to serve binary content, you shouldn't also use the writer (which you're writing "Hello, world" with).
If you change your first couple of lines to:
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment;filename=sample.pdf");
you may find that's all that's required.