HTML5拖拽文件到瀏覽器并實(shí)現(xiàn)文件上傳下載功能代碼
來源:易賢網(wǎng) 閱讀:2178 次 日期:2016-07-13 14:45:39
溫馨提示:易賢網(wǎng)小編為您整理了“HTML5拖拽文件到瀏覽器并實(shí)現(xiàn)文件上傳下載功能代碼”,方便廣大網(wǎng)友查閱!

使用HTML5拖拽文件到瀏覽器并實(shí)現(xiàn)文件上傳下載,html5的功能是越來越強(qiáng)大了,下面與大家分享下具體的實(shí)現(xiàn)代碼,感興趣的朋友可以參考下

先上代碼,寫的jsp頁面,后臺(tái)是tomcat服務(wù)器,所以頁面里有一些java的代碼,如果后臺(tái)用其他語言可以無視:

代碼如下:

<%@ 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代碼,顯示服務(wù)器上可以供下載的文件

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異步傳輸數(shù)據(jù)

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); //由于這個(gè)頁面還要顯示可以下載的文件,所以需要刷新下頁面

}

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>

附上后臺(tái)處理上傳下載的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;

}

}

}

更多信息請(qǐng)查看網(wǎng)頁制作
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國考·省考課程試聽報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)