【转】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" οnsubmit="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");
 }
}

本文转自编程中国社区,作者@三公主

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dropzone 是一个基于 HTML、CSS 和 JavaScript 的开源库,用于实现拖拽上传文件的功能。Dropzone 具有强大的可扩展性和自定义性,可以很容易地集成到你的项目中。 使用 Dropzone 实现拖拽上传文件并回显的代码如下: HTML: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用 Dropzone 拖拽上传文件</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dropzone/dist/dropzone.css"> </head> <body> <form action="upload.php" class="dropzone" id="my-dropzone"></form> <ul id="file-list"></ul> <script src="https://cdn.jsdelivr.net/npm/dropzone"></script> <script src="upload.js"></script> </body> </html> ``` JavaScript: ```javascript Dropzone.autoDiscover = false; var myDropzone = new Dropzone("#my-dropzone", { url: "upload.php", paramName: "file", maxFilesize: 2, // 上传文件大小限制,单位为 MB maxFiles: 10, // 最多上传文件数量限制 addRemoveLinks: true, // 是否显示删除链接 dictRemoveFile: '删除文件', // 删除文件的链接文字 dictDefaultMessage: '将文件拖到此处上传', // 默认的提示消息 dictFallbackMessage: '您的浏览器不支持拖拽上传文件', // 浏览器不支持拖拽上传时的提示消息 dictFileTooBig: '文件大小超过限制', // 文件大小超过限制时的提示消息 dictInvalidFileType: '文件类型不支持', // 文件类型不支持时的提示消息 init: function() { this.on("success", function(file, response) { console.log(response); // 回显上传成功的文件信息 // 显示文件列表 var li = document.createElement('li'); li.innerHTML = file.name; document.getElementById('file-list').appendChild(li); }); } }); ``` 在上面的代码中,我们首先将 Dropzone 的样式文件和库文件引入到 HTML 中,然后在 HTML 文件中添加一个表单,表单的 class 设置为 `dropzone`,id 设置为 `my-dropzone`,这样就可以让 Dropzone 自动将表单换为拖拽上传区域。在 JavaScript 中,我们首先设置了 `Dropzone.autoDiscover = false;`,这样就不会自动扫描 HTML 中的表单进行换,而是通过 `new Dropzone()` 的方式来初始化 Dropzone。在初始化时,我们通过 `url` 参数指定了上传文件的处理地址,通过 `paramName` 参数指定了文件参数名,通过 `maxFilesize` 和 `maxFiles` 参数分别设置了上传文件大小和数量的限制,通过 `addRemoveLinks` 和 `dictRemoveFile` 参数控制是否显示删除链接和删除链接的文字。在 `init` 回调函数中,我们通过 `success` 事件回调函数来获取上传成功的文件信息并回显到页面上。 需要注意的是,因为上传文件使用了 `Dropzone` 对象,所以需要使用服务器端代码来进行处理,这里使用了 `upload.php` 来处理上传文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值