uploadify组件文件上传那些事

简介: uploadify组件文件上传那些事

从一个异常引起的,TypeError: $("#file_upload").uploadify is not a function,其实就是使用uploadify组件上传文件,但是一直报莫名其妙的错误。网上众说纷纭…在此记录并上传调试好的源码


【1】uploadify组件

uploadify官网:http://www.uploadify.com/ 但是从这里下载好像付费,文章末尾会附上源码和插件下载地址。

页面源码

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>UploadiFive Test</title>
<link rel="stylesheet" type="text/css" href="/UeditorWeb/uploadifive.css"/>
<script type="text/javascript" src="/UeditorWeb/jquery.min.js"></script>
<script type="text/javascript" src="/UeditorWeb/jquery.uploadifive.min.js"></script>
<style type="text/css">
body {
  font: 13px Arial, Helvetica, Sans-serif;
}
.uploadifive-button {
  float: left;
  margin-right: 10px;
}
#queue {
  border: 1px solid #E5E5E5;
  height: 177px;
  overflow: auto;
  margin-bottom: 10px;
  padding: 0 3px 3px;
  width: 300px;
}
</style>
</head>
<body>
  <form>
    <div id="queue"></div>
    <input id="file_upload" name="file_upload" type="file" multiple="true">
    <a style="position: relative; top: 8px;" href="javascript:$('#file_upload').uploadifive('upload')">Upload Files</a>
  </form>
  <script type="text/javascript">
    $(function() {
      $('#file_upload').uploadifive({
        'auto'             : false,
        'formData'         : {
                     'timestamp' : '111',
                     'token'     : '111'
                             },
        'queueID'          : 'queue',
        'uploadScript'     : '/UeditorWeb/upload',
        'onUploadComplete' : function(file, data) { console.log(data); }
      });
    });
  </script>
</body>
</html>

【2】修改后的Huploadify组件

页面源码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link rel="stylesheet" type="text/css" href="/UeditorWeb/Huploadify.css"/>
<script type="text/javascript" src="/UeditorWeb/jquery.js"></script>
<script type="text/javascript" src="/UeditorWeb/jquery.Huploadify.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
$(function(){
  $('#upload').Huploadify({
    auto:true,
    fileTypeExts:'*.jpg;*.png;*.exe',
    multi:true,
    formData:{pid:'portal',token:'portal',filedesc:''},
    fileSizeLimit:9999,
    showUploadedPercent:true,//是否实时显示上传的百分比,如20%
    showUploadedSize:true,
    removeTimeout:9999999,
    uploader : '/UeditorWeb/upload',
    onUploadStart:function(){
      //alert('开始上传');
      },
    onInit:function(){
      //alert('初始化');
      },
    onUploadComplete:function(){
      //alert('上传完成');
      },
      onUploadSuccess: function(file, data, response) {
          alert(data);
        },
    onDelete:function(file){
      console.log('删除的文件:'+file);
      console.log(file);
    }
    });
  });
</script>
</head>
<body>
<div id="upload"></div>
</body>
</html>

每次选择文件都会直接上传,下面会有一个进度条示意。

后台对应代码

就是很常见的文件上传。

package com.web.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID;
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.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
  /**
   * 
   */
  private static final long serialVersionUID = 8382832509729035231L;
//  private ShFileDataService shFileDataService = SpringContextHolder.getBean("shFileDataService");
  /**
   * Constructor of the object.
   */
  public FileUploadServlet() {
    super();
  }
  /**
   * Destruction of the servlet. <br>
   */
  public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
  }
  /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   * 
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request,response);
  }
  /**
   * The doPost method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to post.
   * 
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      String fileSize = "";
       String savePath =
       this.getServletContext().getRealPath("/WEB-INF/upload");
       String tempPath =
       this.getServletContext().getRealPath("/WEB-INF/temp");
      File tmpFile = new File(tempPath);
      if (!tmpFile.exists()) {
        tmpFile.mkdir();
      }
      String message = "";
      try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 100);
        factory.setRepository(tmpFile);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setProgressListener(new ProgressListener() {
          public void update(long pBytesRead, long pContentLength,
              int arg2) {
          }
        });
        upload.setHeaderEncoding("UTF-8");
        if (!ServletFileUpload.isMultipartContent(request)) {
          return;
        }
        upload.setFileSizeMax(1024 * 1024 * 5);
        upload.setSizeMax(1024 * 1024 * 10);
        List<FileItem> list = upload.parseRequest(request);
        for (FileItem item : list) {
          //if (item.isFormField()) {
            //String name = item.getFieldName();
            //String value = item.getString("UTF-8");
            // value = new
        //  } else {// ���fileitem�з�װ�����ϴ��ļ�
            String filename = item.getName();
            Long filesizeNum = (Long) item.getSize();
            if (filesizeNum > 0) {
              DecimalFormat df = new DecimalFormat("####.00");
              float size = (float) filesizeNum / 1024;
              fileSize = df.format(size);
            }
            if (filename == null || filename.trim().equals("")) {
              continue;
            }
            filename = filename.substring(filename
                .lastIndexOf("\\") + 1);
            String fileExtName = filename.substring(filename
                .lastIndexOf(".") + 1);
            InputStream in = item.getInputStream();
            String saveFilename = makeFileName(filename);
            String realSavePath = makePath(saveFilename, savePath);
            FileOutputStream out = new FileOutputStream(
                realSavePath + "\\" + saveFilename);
            byte buffer[] = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
              out.write(buffer, 0, len);
            }
            out.close(); 
            in.close();
            String  href = realSavePath+"\\"+saveFilename;
            StringBuilder resultHtml = new StringBuilder();
            resultHtml.append(" <li id='file_SWFUpload_5_0' style='font-size: 16px;margin-left: 25px;padding: 5px;'> ");
            resultHtml.append(" <span class='attch-name'>"+ filename);
            resultHtml.append(" <span class='attch-size'>"
                    + fileSize
                    + "KB</span><span class='attch-state' style='color:#c1c1c1'>(���)</span>");
            resultHtml.append(" <a style='color: #178be2' target='_blank' href='"+href+"' class='attch-dload'>����</a>");
//            resultHtml.append(" <a style='color: #178be2' id='"+shFileData.getFileId()+"' class='attch-delete'>ɾ��</a>");
            resultHtml.append(" </li>");
            response.getWriter().write(resultHtml.toString());
          //}
        }
      } catch (FileUploadBase.FileSizeLimitExceededException e) {
        request.setAttribute("message", "the file is too big");
        return;
      } catch (FileUploadBase.SizeLimitExceededException e) {
        request.setAttribute("message", "the file is too big");
        return;
      } catch (Exception e) {
        message = "file upload fail";
        request.setAttribute("message", "file upload fail");
      }
      request.setAttribute("message", message);
  }
  /**
   * Initialization of the servlet. <br>
   *
   * @throws ServletException if an error occurs
   */
  public void init() throws ServletException {
  }
  private String makeFileName(String filename) { // 2.jpg
    return UUID.randomUUID().toString() + "_" + filename;
  }
  private String makePath(String filename, String savePath) {
    String dir = savePath;
    File file = new File(dir);
    if (!file.exists()) {
      file.mkdirs();
    }
    return dir;
  }
}

项目和组件下载地址


下载内容示意:

目录
相关文章
|
1月前
|
前端开发
前端通过input标签封装Upload组件实现文件上传
前端通过input标签封装Upload组件实现文件上传
53 0
|
5月前
LayUI upload上传组件上传文件的两种方式
LayUI upload上传组件上传文件的两种方式
385 0
|
JavaScript 前端开发
uploadify图片上传插件使用实例
1、uploadify插件库引用 2、uploadify应用代码 $('#uploadify').uploadify({ 'uploader': '.
1024 0
|
JavaScript 前端开发
js之上传文件多图片预览
多图片上传预览功能也是现在非常常用的 下面是html代码: 测试页面 //下面用于多图片上传预览功能 function setImagePreviews(avalue) { var docObj = document.
1183 0
|
存储 前端开发 JavaScript
移动端实现多图上传、文件上传及下载和vue多图片上传组件
js+css实现手机端的多图片上传,为了方便使用,css和js都未内联,为性能建议使用时改为外联; 如要用到pc端,直接去掉px转换为rem的js代码,修改单位即可; 因multiple在安卓手机中不兼容,所以在安卓上只能一次选中一张图片,在iOS系统...
5291 0
|
JavaScript 内存技术
|
JavaScript 前端开发 内存技术
|
JavaScript 前端开发