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>");
});
});
Supported File Types
1. Image FIle Extensions mime type extension image/jpeg jpg image/pjpeg jpg image/gif gif image/png png image/tiff tiff image/bmp bmp image/x-ms-bmp bmp
2. Audio File Extensions mime type extension audio/mp3 mp3 audio/mpeg mp3 audio/mpeg3 mp3 audio/mp4 mp4 audio/ogg ogg audio/x-ms-wma wma audio/x-wav wav
3. Video Files Extensions mime type extension video/avi avi video/x-ms-wmv wmv video/mpeg mpg video/quicktime mov video/ogg ogg video/x-flv flv video/mp4 mp4 video/3gp 3gp video/3gpp 3gp video/3gpp2 3g2 video/x-dv dv video/x-m4v m4v video/x-ms-asf asf
4. Document File Extensions mime type extension text/plain txt text/html html text/rtf rtf application/rtf rtf application/ogg ogg application/pdf application/msword doc application/vnd.ms-office doc application/vnd.openxmlformats-officedocument.wordprocessingml.document docx application/vnd.ms-word.document.macroEnabled.12 docm application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx application/ms-excel xls application/excel xls application/vnd.ms-excel xls application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx application/powerpoint ppt application/vnd.ms-powerpoint ppt application/vnd.openxmlformats-officedocument.presentationml.presentation pptx
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