Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to upload a file using commons file upload streaming api

Tags:

java

jsp

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.

like image 357
qualebs Avatar asked Mar 15 '13 12:03

qualebs


People also ask

Can we upload file using REST API?

You can use this parameter to set metadata values to a collection already assigned to any parent folder. The rules are the same as those applied to the set metadata values REST API. Use Content-Type: application/json to describe this information as a JSON object. File to upload.


1 Answers

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();
    }
}
like image 142
madhairsilence Avatar answered Sep 19 '22 19:09

madhairsilence