Comments: Using HTML5 to drag files to a browser and upload and download files, html5 is becoming more and more powerful. I will share with you the specific implementation code below. If you are interested, please refer
First, the code is written on the jsp page, and the background is the tomcat server. Therefore, the page contains some java code, which can be ignored if other languages are used in the background:
The Code is as follows:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8"
PageEncoding = "UTF-8" %>
<% @ Page import = "java. io. *" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> upload and download files </title>
<Style type = "text/css">
# Filedrag {
Display: none;
Font-weight: bold;
Text-align: center;
Padding: 1em 0;
Margin: 1em 0;
Color: #555;
Border: 2px dashed #555;
Border-radius: 7px;
Cursor: default;
}
# Filedrag. hover {
Color: # f00;
Border-color: # f00;
Border-style: solid;
Box-shadow: inset 0 3px 4px #888;
}
</Style>
</Head>
<Body>
<Form id = "upload" action = "UploadServlet" enctype = "multipart/form-data"
Method = "post" onsubmit = "return upLoad ();">
<P>
<Label for = "fileselect"> file name: </label> <input multiple = "true"
Type = "file" id = "fileselect" name = "fileselect []"/>
<Div id = "filedrag"> or drag the file here </div>
<Div id = "submitbutton">
<Input type = "submit" value = "submit">
</Div>
</Form>
<Div id = "messages">
</Div>
<% // Java code to display files available for download on the server
File f = new File ("G: // defggg /");
File [] list = f. listFiles ();
For (int I = 0; I <list. length; ++ I ){
System. out. println (list [I]. getName ());
Out. print ("<a href = 'downloadservlet? Filename ="
+ List [I]. getName () + "'>" + list [I]. getName ()
+ "</A> <br/> ");
}
%>
<Script type = "text/javascript">
Var upfiles = new Array ();
// GetElementById
Function $ id (id ){
Return document. getElementById (id );
}
// Output information
Function Output (msg ){
Var m = $ id ("messages ");
M. innerHTML = msg + m. innerHTML;
}
// File drag hover
Function FileDragHover (e ){
E. stopPropagation ();
E. preventDefault ();
E.tar get. className = (e. type = "dragover "? "Hover ":"");
}
// File selection
Function FileSelectHandler (e ){
// Cancel event and hover styling
FileDragHover (e );
// Fetch FileList object
Var files = e.tar get. files | e. dataTransfer. files;
// Process all File objects
For (var I = 0, f; f = files [I]; I ++ ){
ParseFile (f );
Upfiles. push (f );
}
}
// Output file information
Function ParseFile (file ){
Output ("<p> file information: <strong>" + file. name
+ "</Strong> type: <strong>" + file. type
+ "</Strong> size: <strong>" + file. size
+ "</Strong> bytes </p> ");
}
Function upLoad (){
If (upfiles [0]) {
Var xhr = new XMLHttpRequest (); // Ajax asynchronously transmits data
Xhr. open ("POST", "UploadServlet", true );
Var formData = new FormData ();
For (var I = 0, f; f = upfiles [I]; I ++ ){
FormData. append ('myfile', f );
}
Xhr. send (formData );
Xhr. onreadystatechange = function (e ){
History. go (0); // because this page also displays downloadable files, you need to refresh the page
}
Return false;
}
}
// Initialize
Function Init (){
Var fileselect = $ id ("fileselect"), filedrag = $ id ("filedrag"), submitbutton = $ id ("submitbutton ");
// File select
Fileselect. addEventListener ("change", FileSelectHandler, false );
// Is XHR2 available?
Var xhr = new XMLHttpRequest ();
If (xhr. upload ){
// File drop
Filedrag. addEventListener ("dragover", FileDragHover, false );
Filedrag. addEventListener ("dragleave", FileDragHover, false );
Filedrag. addEventListener ("drop", FileSelectHandler, false );
Filedrag. style. display = "block ";
// Remove submit button
// Submitbutton. style. display = "none ";
}
}
// Call initialization file
If (window. File & window. FileList & window. FileReader ){
Init ();
}
</Script>
</Body>
</Html>
The servlet used to process uploads and downloads in the background is attached, and smartUpLoad is used, which cannot solve the Chinese problem well:
The Code is as follows:
Package com. hit. software;
Import java. io. IOException;
Import javax. servlet. ServletConfig;
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 com. jspsmart. upload. Files;
Import com. jspsmart. upload. SmartUpload;
/**
* Servlet implementation class UploadServlet
*/
@ WebServlet ("/UploadServlet ")
Public class UploadServlet extends HttpServlet {
Private static final long serialVersionUID = 1L;
Private ServletConfig config;
Final public void init (ServletConfig config) throws ServletException {
This. config = config;
}
/**
* @ See HttpServlet # HttpServlet ()
*/
Public UploadServlet (){
Super ();
// TODO Auto-generated constructor stub
}
/**
* @ See HttpServlet # doGet (HttpServletRequest request, HttpServletResponse
* Response)
*/
Protected void doGet (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
DoPost (request, response );
}
/**
* @ See HttpServlet # doPost (HttpServletRequest request, HttpServletResponse
* Response)
*/
Protected void doPost (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Request. setCharacterEncoding ("UTF-8 ");
// String s = request. getParameter ("pic ");
// System. out. println (s );
SmartUpload mySmartUpload = new SmartUpload ();
Try {
MySmartUpload. initialize (config, request, response );
MySmartUpload. setMaxFileSize (150*1024*1024 );
MySmartUpload. setTotalMaxFileSize (150*1024*1024 );
// MySmartUpload. setAllowedFilesList ("doc, txt, rar, pdf, png ");
MySmartUpload. setDeniedFilesList ("exe ");
MySmartUpload. upload ();
Files f = mySmartUpload. getFiles ();
Int size = f. getCount ();
For (int I = 0; I <size; ++ I ){
String fileName = mySmartUpload. getFiles (). getFile (I)
. GetFileName ();
FileName = new String (fileName. trim (). getBytes (), "UTF-8"); // solves some Chinese problems
System. out. println ("filename =" + fileName );
If (! FileName. equals ("")){
String path = "g:/defggg/" + fileName;
F. getFile (I). saveAs (path, SmartUpload. SAVE_PHYSICAL );
}
}
} Catch (Exception e ){
E. printStackTrace ();
System. out. println ("Unable to upload the file .");
System. out. println ("Error:" + e. toString ());
}
Response. sendRedirect ("index. jsp ");
}
}
The Code is as follows:
Package com. hit. software;
Import java. io. File;
Import java. io. IOException;
Import javax. servlet. ServletConfig;
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 javax. servlet. jsp. JspFactory;
Import javax. servlet. jsp. JspWriter;
Import javax. servlet. jsp. PageContext;
Import com. jspsmart. upload. SmartUpload;
Import com. jspsmart. upload. SmartUploadException;
/**
* Servlet implementation class DownloadServlet
*/
@ WebServlet ("/DownloadServlet ")
Public class DownloadServlet extends HttpServlet {
Private static final long serialVersionUID = 1L;
Private ServletConfig config;
/**
* @ See HttpServlet # HttpServlet ()
*/
Public DownloadServlet (){
Super ();
// TODO Auto-generated constructor stub
}
Final public void init (ServletConfig config) throws ServletException {
This. config = config;
}
/**
* @ See HttpServlet # doGet (HttpServletRequest request, HttpServletResponse
* Response)
*/
Protected void doGet (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
DoPost (request, response );
}
/**
* @ See HttpServlet # doPost (HttpServletRequest request, HttpServletResponse
* Response)
*/
Protected void doPost (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Request. setCharacterEncoding ("UTF-8 ");
String fileName = request. getParameter ("filename ");
System. out. println ("down:" + fileName );
If (fileName = null ){
Response. sendRedirect ("index. jsp ");
Return;
}
FileName = "G: // defggg //" + fileName;
File f = new File (fileName );
If (f. exists () & f. isFile ()){
SmartUpload su = new SmartUpload ();
Su. initialize (config, request, response );
Su. setContentDisposition (null );
Try {
Su. downloadFile (fileName );
} Catch (SmartUploadException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
} Else {
Response. sendRedirect ("index. jsp ");
Return;
}
}
}