28 October 2016

Upload File Processing Image Audio Video [Ajax] Java Servlet JSP (Hỗ trợ nhiểu loại file Upload)

Cấu trúc của project
-Tạo trang index.jsp chứa form 
index.jsp
Java Web  2016
<!DOCTYPE html>
<html>
    <head>
        <title>Image Upload and Resize</title>
        <link href="css/style.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <div class="form-wrap">
            <h3>Ajax Image Uploader Java Servlet</h3>
            <form action="UploadFile" method="post" enctype="multipart/form-data" id="upload_form">
                <input name="myfile" type="file" multiple/>
                <input name="submit" type="submit" value="Upload"/>
            </form>
            <div id="progress-wrp"><div class="progress-bar"></div ><div class="status">0%</div></div>
            <div id="output"><!-- error or success results --></div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script>
        <script src="js/Upload_Input_Process_Output.js" type="text/javascript"></script>
    </body>
</html>
-Tạo servlet có method Upload trong package com.giaima
UploadFile.java
Java Web  2016
package com.giaima;

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;

public class UploadFile extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private final String UPLOAD_DIRECTORY = "e:/";

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        //Fix UTF-8
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8");

        // process only if its multipart content
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            Upload(request);
        }

    }

    public void Upload(HttpServletRequest request) {

        // 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));
                }
            }
        } catch (Exception e) {
            System.out.println("File upload failed");
        }

    }
}
Upload_Input_Process_Output.js
Java Web  2016
//configuration
var max_file_size = 20485760000; //allowed file size. (1 MB = 1048576)
var allowed_file_types = ['video/mp4','audio/mp3', 'image/png', 'image/gif', 'image/jpeg', 'image/pjpeg']; //allowed file types
var result_output = '#output'; //ID of an element for response output
var my_form_id = '#upload_form'; //ID of an element for response output
var progress_bar_id = '#progress-wrp'; //ID of an element for response output
var total_files_allowed = 3; //Number files allowed to upload

//on form submit
$(my_form_id).on("submit", function (event) {
    event.preventDefault();
    var proceed = true; //set proceed flag
    var error = []; //errors
    var total_files_size = 0;

    //reset progressbar
    $(progress_bar_id + " .progress-bar").css("width", "0%");
    $(progress_bar_id + " .status").text("0%");

    if (!window.File && window.FileReader && window.FileList && window.Blob) { //if browser doesn't supports File API
        error.push("Your browser does not support new File API! Please upgrade."); //push error text
    } else {
        var total_selected_files = this.elements['myfile'].files.length; //number of files

        //limit number of files allowed
        if (total_selected_files > total_files_allowed) {
            error.push("You have selected " + total_selected_files + " file(s), " + total_files_allowed + " is maximum!"); //push error text
            proceed = false; //set proceed flag to false
        }
        //iterate files in file input field
        $(this.elements['myfile'].files).each(function (i, ifile) {
            if (ifile.value !== "") { //continue only if file(s) are selected
                if (allowed_file_types.indexOf(ifile.type) === -1) { //check unsupported file
                    error.push("<b>" + ifile.name + "</b> is unsupported file type!"); //push error text
                    proceed = false; //set proceed flag to false
                }

                total_files_size = total_files_size + ifile.size; //add file size to total size
            }
        });

        //if total file size is greater than max file size
        if (total_files_size > max_file_size) {
            error.push("You have " + total_selected_files + " file(s) with total size " + total_files_size + ", Allowed size is " + max_file_size + ", Try smaller file!"); //push error text
            proceed = false; //set proceed flag to false
        }

        var submit_btn = $(this).find("input[type=submit]"); //form submit button 

        //if everything looks good, proceed with jQuery Ajax
        if (proceed) {
            //submit_btn.val("Please Wait...").prop( "disabled", true); //disable submit button
            var form_data = new FormData(this); //Creates new FormData object
            var post_url = $(this).attr("action"); //get action URL of form

            //jQuery Ajax to Post form data
            $.ajax({
                url: post_url,
                type: "POST",
                data: form_data,
                contentType: false,
                cache: false,
                processData: false,
                xhr: function () {
                    //upload Progress
                    var xhr = $.ajaxSettings.xhr();
                    if (xhr.upload) {
                        xhr.upload.addEventListener('progress', function (event) {
                            var percent = 0;
                            var position = event.loaded || event.position;
                            var total = event.total;
                            if (event.lengthComputable) {
                                percent = Math.ceil(position / total * 100);
                            }
                            //update progressbar
                            $(progress_bar_id + " .progress-bar").css("width", +percent + "%");
                            $(progress_bar_id + " .status").text(percent + "%");
                        }, true);
                    }
                    return xhr;
                },
                mimeType: "multipart/form-data"
            }).done(function (res) { //
                $(my_form_id)[0].reset(); //reset form
                $(result_output).html(res); //output response from server
                submit_btn.val("Upload").prop("disabled", false); //enable submit button once ajax is done
            });

        }
    }

    $(result_output).html(""); //reset output 
    $(error).each(function (i) { //output any error to output element
        $(result_output).append('<div class="error">' + error[i] + "</div>");
    });

}); 

1. Image FIle Extensions
mime typeextension
image/jpegjpg
image/pjpegjpg
image/gifgif
image/pngpng
image/tifftiff
image/bmpbmp
image/x-ms-bmpbmp
2. Audio File Extensions
mime typeextension
audio/mp3mp3
audio/mpegmp3
audio/mpeg3mp3
audio/mp4mp4
audio/oggogg
audio/x-ms-wmawma
audio/x-wavwav
3. Video Files Extensions
mime typeextension
video/aviavi
video/x-ms-wmvwmv
video/mpegmpg
video/quicktimemov
video/oggogg
video/x-flvflv
video/mp4mp4
video/3gp3gp
video/3gpp3gp
video/3gpp23g2
video/x-dvdv
video/x-m4vm4v
video/x-ms-asfasf
4. Document File Extensions
mime typeextension
text/plaintxt
text/htmlhtml
text/rtfrtf
application/rtfrtf
application/oggogg
application/pdfpdf
application/msworddoc
application/vnd.ms-officedoc
application/vnd.openxmlformats-officedocument.wordprocessingml.documentdocx
application/vnd.ms-word.document.macroEnabled.12docm
application/vnd.openxmlformats-officedocument.wordprocessingml.templatedotx
application/ms-excelxls
application/excelxls
application/vnd.ms-excelxls
application/vnd.openxmlformats-officedocument.spreadsheetml.sheetxlsx
application/powerpointppt
application/vnd.ms-powerpointppt
application/vnd.openxmlformats-officedocument.presentationml.presentationpptx
style.css
Java Web  2016
.form-wrap{
    max-width: 500px;
    padding: 30px;
    background: #f1f1f1;
    margin: 20px auto;
    border-radius: 4px;
 text-align: center;
}
.form-wrap form{
 border-bottom: 1px dotted #ddd;
 padding: 10px;
}
.form-wrap #output{
    margin: 10px 0;
}
.form-wrap .error{
    color: #d60000;
}
.form-wrap .images {
    width: 100%;
    display: block;
    border: 1px solid #e8e8e8;
    padding: 5px;
    margin: 5px 0;
}
.form-wrap .thumbnails {
    width: 32%;
    display: inline-block;
    margin: 3px;
}

/* progress bar */
#progress-wrp {
    border: 1px solid #0099CC;
    padding: 1px;
    position: relative;
    border-radius: 3px;
    margin: 10px;
    text-align: left;
    background: #fff;
    box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}
#progress-wrp .progress-bar{
 height: 20px;
    border-radius: 3px;
    background-color: #f39ac7;
    width: 0;
    box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}
#progress-wrp .status{
 top:3px;
 left:50%;
 position:absolute;
 display:inline-block;
 color: #000000;
}
web.xml
Java Web  2016
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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_3_0.xsd">
    <display-name>AjaxFileUploadBar</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>UploadFile</servlet-name>
        <servlet-class>com.giaima.UploadFile</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadFile</servlet-name>
        <url-pattern>/UploadFile</url-pattern>
    </servlet-mapping>
</web-app>

Download Project (Zip import NetBeans)

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang