您的位置:首页 > 编程语言 > Java开发

springmvc +uploadify 3.2.1 上传文件

2015-10-27 16:22 609 查看
<%@page import="com.ist.pojo.User"%>

<%@page import="com.ist.constant.ConstantField"%>

<%@ page language="java" contentType="text/html; charset=utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>Upload</title>

<!--装载文件-->

<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>

<script src="js/jquery.uploadify.js" type="text/javascript"></script>

<script src="js/jquery.uploadify.min.js" type="text/javascript"></script>

<link href="uploadify.css" rel="stylesheet" type="text/css" />

<%User user = (User)request.getSession().getAttribute(ConstantField.LOGIN_USER); %>

<!--ready事件-->

<script type="text/javascript">

 $(document).ready(function () {

  var fileType ="${param.fileType}";

     var userName = "<%=user.getUsName() %>";

        $("#uploadify").uploadify({

            'cancelImage': 'cancel.png',

            'auto': false,

            'successTimeout': 99999,

            'swf': 'uploadify.swf',

            'queueID': 'fileQueue',

            'uploader': '../uploadDFS/upload.do?fileType='+fileType+'&userName='+userName,

            'fileSizeLimit': '0',

            'fileTypeExts': '*.gif; *.jpeg; *.jpg; *.png',

            'multi': true,

            'method':'post',

            'queueSizeLimit': 10,

            'buttonText':'选择文件',

            //'formData': { 'fileType':1,'userName':'admin' },//这里只能传静态参数

            onSelectError: function (file, errorCode, errorMsg) {

                switch (errorCode) {

                    case -100:

                        alert("上传的文件数量已经超出系统限制的" + $('#uploadify').uploadify('settings', 'queueSizeLimit') + "个文件!");

                        break;

                    case -110:

                        alert("文件 [" + file.name + "] 大小超出系统限制的" + $('#uploadify').uploadify('settings', 'fileSizeLimit') + "大小!");

                        break;

                    case -120:

                        alert("文件 [" + file.name + "] 大小异常!");

                        break;

                    case -130:

                        alert("文件 [" + file.name + "] 类型不正确!");

                        break;

                }

            },

            'onUploadStart': function (file) {

              var param = {};

              param.fileType = fileType;

              param.userName = userName;

               $("#uploadify").uploadify("settings","formData",param);

               //在onUploadStart事件中,也就是上传之前,把参数写好传递到后台。

            },'onUploadSuccess':function(file, data, response){ 

             alert("文件:" + file.name + "上传成功");  

 

            },'onUploadError' : function(file, errorCode, errorMsg, errorString) {    

             alert("文件:" + file.name + "上传失败");    

            } 

        });

    });

</script>

</head>

<body> 

    <form id="form1" runat="server" enctype="multipart/form-data"> 

    <div id="fileQueue">        

    </div> 

        <div> 

            <p> 

                <input type="file" name="uploadify" id="uploadify"/>

                <input id="Button1" type="button" value="上传" onclick="javascript: $('#uploadify').uploadify('upload','*')" /> 

                <input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadify('cancel','*')" /> 

            </p> 

        </div> 

    </form> 

</body>

</html>

 

 

action类

 @RequestMapping("/upload.do")

    @ResponseBody

 public String upload (HttpServletRequest request){

     //request.getParameter()只能获取url ?后面的参数

     int fileType = Integer.parseInt(request.getParameter("fileType"));

     String userName = request.getParameter("userName");

     User user = new User();

     user.setUsName(userName);

  String path="";

  try {

   request.setCharacterEncoding("utf-8");

  } catch (UnsupportedEncodingException e1) {

   // TODO Auto-generated catch block

   e1.printStackTrace();

  }

  DiskFileItemFactory factory = new DiskFileItemFactory();

  factory.setSizeThreshold(1024*1024) ;

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setHeaderEncoding("UTF-8");//关键

        upload.setSizeMax(200000000);

        try {

            //可以上传多个文件

            List<FileItem> list = (List<FileItem>)upload.parseRequest(request);

           //获取formdata参数

           Map<String,Object> formData = getItemFiled(list);

            for(int i=0;i<list.size();i++){

             FileItem item = list.get(i); 

                if(!item.isFormField()){

                    String name = item.getName() ;

                    String fileExtName  = name.substring(name.lastIndexOf(".")+1,name.length());

                    String oldName = name.replaceAll("." + fileExtName,"");

                   

                    InputStream in = item.getInputStream();

                    byte[] content = getInputStreamToByte(in);

                   

                 DFSFile dfsfile = new DFSFile(oldName, content,fileExtName,fileType);

                 dfsfile.setFileLength(item.getSize());

                 NameValuePair[] metaList = new NameValuePair[3]; 

                    metaList[0] = new NameValuePair("fileName", name); 

                    metaList[1] = new NameValuePair("fileExtName", fileExtName); 

                    metaList[2] = new NameValuePair("fileLength", String.valueOf(item.getSize())); 

                   

                    path = fastService.upload(dfsfile ,metaList,user);

                 

                    break;

                }

            }        

        }catch (Exception e) {

            System.out.println("出错了:" + e.getMessage());

        }

       

        return "1";

 }

 

    /**

     * 获取uploadify的formdata Map集合

     * @param list

     * @return

     */

    public Map<String,Objec
4000
t> getItemFiled(List<FileItem> list){

      Map<String,Object> results = new HashMap<String,Object>();

      for(int i=0;i<list.size();i++){

          FileItem item = list.get(i);

          if(item.isFormField()){

           String key = item.getFieldName();

           String value = item.getString();

           results.put(key, value);

          }

      }

      return results;

    }

   /**

     * 把inputStream流转换成字节数组

     * @param in

     * @return

     */

    public byte[] getInputStreamToByte(InputStream in){

     byte[] file_buff = null;

     try{

      

        if (in != null) {

         int len = in.available();

         file_buff = new byte[len];

         in.read(file_buff);

        }

     }catch(Exception e){

       System.out.println("出错了:" + e.getMessage());

       }

       return file_buff;

    }

 

service类

 

/**

  * 文件上传

  * @param file

  * @return

  */

 public String upload(DFSFile file,NameValuePair[] metaList,User user) {

  log.info("File Name: " + file.getName() + "  File Length: " + file.getContent().length);

  //NameValuePair[] meta_list = new NameValuePair[3];

  //meta_list[0] = new NameValuePair("width", "120");

  //meta_list[1] = new NameValuePair("heigth", "120");

  //meta_list[2] = new NameValuePair("author", "admin");

  long startTime = System.currentTimeMillis();

  String[] uploadResults = null;

  try {

   uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), metaList);

  } catch (IOException e) {

   log.error("io异常:上传文件 " + file.getName(), e);

  } catch (Exception e) {

   log.error("非io异常:上传文件 " + file.getName(), e);

  }

  log.info("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms");

  if (uploadResults == null) {

   log.error("上传文件失败, 错误码: " + storageClient.getErrorCode());

  }

  String groupName = uploadResults[0];

  String remoteFileName = uploadResults[1];

  //保存Marterial素材对象和FileType文件对象

  saveMarterialAndFileType(user, file, remoteFileName);

  

  String fileAbsolutePath = ConstantField.PROTOCOL + trackerServer.getInetSocketAddress().getHostName() + ConstantField.SEPARATOR

    + ConstantField.TRACKER_NGNIX_PORT + ConstantField.SEPARATOR + groupName + ConstantField.SEPARATOR + remoteFileName;

  log.info("上传文件成功!  " + "组名: " + groupName + ", 文件名:" + " "

    + remoteFileName);

  return fileAbsolutePath;

 }

 

dfsfile类

public class DFSFile {

 //原文件名称,不含结尾字符串

 private String name;

 //文件内容 字节类型

 private byte[] content;

 //文件结尾

 private String ext;

 

 private String height;

 

 private String width;

 

 private String author;

 

 private Long fileLength;

 

 private int fileType;

 

 public DFSFile(String name, byte[] content, String ext, String height,

   String width, String author,int fileType) {

  super();

  this.name = name;

  this.content = content;

  this.ext = ext;

  this.height = height;

  this.width = width;

  this.author = author;

  this.fileType = fileType;

 }

 

 public DFSFile(String name, byte[] content, String ext,int fileType) {

  super();

  this.name = name;

  this.content = content;

  this.ext = ext;

  this.fileType = fileType;

 }

 

 public DFSFile(String ext,Long fileLength,int fileType) {

  this.ext = ext;

  this.fileLength = fileLength;

  this.fileType = fileType;

 }

 public byte[] getContent() {

  return content;

 }

 public void setContent(byte[] content) {

  this.content = content;

 }

 public String getExt() {

  return ext;

 }

 public void setExt(String ext) {

  this.ext = ext;

 }

 public String getHeight() {

  return height;

 }

 public void setHeight(String height) {

  this.height = height;

 }

 public String getWidth() {

  return width;

 }

 public void setWidth(String width) {

  this.width = width;

 }

 public String getAuthor() {

  return author;

 }

 public void setAuthor(String author) {

  this.author = author;

 }

 public String getName() {

  return name;

 }

 public void setName(String name) {

  this.name = name;

 }

 public Long getFileLength() {

  return fileLength;

 }

 public void setFileLength(Long fileLength) {

  this.fileLength = fileLength;

 }

 public int getFileType() {

  return fileType;

 }

 public void setFileType(int fileType) {

  this.fileType = fileType;

 }

 

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc uploadify