首页前端开发HTMLHTML5拖拽文件到浏览器并实现文件上传下载功能代码

HTML5拖拽文件到浏览器并实现文件上传下载功能代码

时间2024-01-24 08:15:29发布访客分类HTML浏览403
导读:收集整理的这篇文章主要介绍了HTML5拖拽文件到浏览器并实现文件上传下载功能代码,觉得挺不错的,现在分享给大家,也给大家做个参考。 先上代码,写的jsp页面,后台是tomcat服务器,所以页面里有一些java的代码,如果后台用其他...
收集整理的这篇文章主要介绍了HTML5拖拽文件到浏览器并实现文件上传下载功能代码,觉得挺不错的,现在分享给大家,也给大家做个参考。

先上代码,写的jsp页面,后台是tomcat服务器,所以页面里有一些java的代码,如果后台用其他语言可以无视:

复制代码代码如下:
%@ 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> 上传、下载文件/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"> 或者将文件拖拽到这里/div>
div id="submitbutton">
input type="submit" value="提交">
/div>
/form>
div id="messages">
/div>
% //java代码,显示服务器上可以供下载的文件
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.target.classname = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.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> 文件信息: strong> " + file.name
+ "/strong> 类型: strong> " + file.type
+ "/strong> 大小: strong> " + file.size
+ "/strong> bytes/p> ");
}
function upLoad() {
if (upfiles[0]) {
var xhr = new XMLHttpRequest(); //Ajax异步传输数据
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); //由于这个页面还要显示可以下载的文件,所以需要刷新下页面
}
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>

附上后台处理上传下载的servlet,用了smartUpLoad,不能很好的解决中文问题:

复制代码代码如下:
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"); //能解决部分中文问题
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");
}
}


复制代码代码如下:
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;
}
}
}

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

浏览器

若转载请注明出处: HTML5拖拽文件到浏览器并实现文件上传下载功能代码
本文地址: https://pptw.com/jishu/585190.html
基于HTML5 Canvas:字符串,路径,背景,图片的详解 HTML5视频支持检测(检查浏览器是否支持视频播放)

游客 回复需填写必要信息