Reputation: 1381
I am following the example provided in the commons file upload site about streaming API. I am stuck trying to figure out how to get the file extension of the uploaded file, how to write the file to a directory and the worst part is where the person who wrote the example comments // Process the input stream...
It leaves me wondering if it's something so trivial that I'm the only one who doesn't know how to.
Upvotes: 8
Views: 44468
Reputation: 1044
The problem with all of these answers is that IT DOESN'T ANSWER THE ORIGINAL QUESTION!!
As it says "process the input stream" it really confuses you what to do next. I was looking at this question all last night trying to find a hint from one of the answers, but nothing. I went and tried other sites, and nothing.
The thing is, what we are doing is out of File Upload's scope, and that is the problem.
We are now working with Java.IO InputStream
InputStream stream = item.openStream();
now we work with that "stream."
Here you can find all sorts of answers to what you need. It's pretty silly that it's so vague, and makes it seem like you have to do something extra with Commons, but in reality it's not commons InputStream it's Java.io's!
In our case we take the stream we are given and upload to a new file by reading byte data
This site also has a bunch of options that might be useful http://www.jedi.be/blog/2009/04/10/java-servlets-and-large-large-file-uploads-enter-apache-fileupload/
I hope this helps others who are confused and new to FileUploading, because I just figured this out a few minutes before writing this answer.
Here is my code that saves a file to the root drive.
try {
System.out.println("sdfk");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext())
{
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
File f = new File("/"+item.getName());
System.out.println(f.getAbsolutePath());
FileOutputStream fout= new FileOutputStream(f);
BufferedOutputStream bout= new BufferedOutputStream (fout);
BufferedInputStream bin= new BufferedInputStream(stream);
int byte_;
while ((byte_=bin.read()) != -1)
{
bout.write(byte_);
}
bout.close();
bin.close();
}
}
catch (FileUploadException ex)
{
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
response.sendRedirect("/plans.jsp");
Good luck!
Upvotes: 5
Reputation: 2050
I have given here http://www.javamonamour.org/2015/10/web-application-for-file-upload-with.html a complete working example (an Eclipse project for WebLogic, but you can easily adapt it to Tomcat).
Otherwise just git clone https://github.com/vernetto/WebFileUploaderStreaming. A complete working example is better than a thousand code snippets.
Upvotes: 0
Reputation: 3870
Use this in your HTML file:
<form action="UploadController" enctype="multipart/form-data" method="post">
<input type="file">
</form>
and in the UploadController
servlet, inside the doPost
method:
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 + "/uploads");
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();
}
}
Upvotes: 9
Reputation: 6286
There's a fantastic 'library' to do this for you. It's actually just a code sample of a Filter that will intercept any form posts of type multipart and give you access to the file, file name etc... which you can handle in your normal servlet post method.
http://balusc.blogspot.com/2007/11/multipartfilter.html
Upvotes: 0
Reputation: 4474
Here is a Servlet that does what you want it to do.
package rick;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;
@WebServlet("/upload4")
public class UploadServlet4 extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("Request content length is " + request.getContentLength() + "<br/>");
out.print("Request content type is " + request.getHeader("Content-Type") + "<br/>");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
FileItemStream item = null;
String name = "";
InputStream stream = null;
while (iter.hasNext()){
item = iter.next();
name = item.getFieldName();
stream = item.openStream();
if(item.isFormField()){out.write("Form field " + name + ": "
+ Streams.asString(stream) + "<br/>");}
else {
name = item.getName();
System.out.println("name==" + name);
if(name != null && !"".equals(name)){
String fileName = new File(item.getName()).getName();
out.write("Client file: " + item.getName() + " <br/>with file name "
+ fileName + " was uploaded.<br/>");
File file = new File(getServletContext().getRealPath("/" + fileName));
FileOutputStream fos = new FileOutputStream(file);
long fileSize = Streams.copy(stream, fos, true);
out.write("Size was " + fileSize + " bytes <br/>");
out.write("File Path is " + file.getPath() + "<br/>");
}
}
}
} catch(FileUploadException fue) {out.write("fue!!!!!!!!!");}
}
}
}
Upvotes: 5