欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现文件上传的两种方法(uploadify和Spring)

程序员文章站 2024-04-01 20:01:22
最近项目中用到的两种文件上传方式做一下总结: 一. uploadify: uploadify控件的scripts和styles在这里: jsp: <...

最近项目中用到的两种文件上传方式做一下总结:

一. uploadify:

uploadify控件的scripts和styles在这里:

jsp:

<%@ page contenttype="text/html;charset=utf-8" language="java" %> 
<%@ include file="../jsp/include/taglibs.jsp"%> 
 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> 
<html> 
 <head> 
 <title>upload</title> 
 <script src="<c:url value="/scripts/jquery-1.8.3.min.js"/>" type="text/javascript"></script> 
 <script type="text/javascript" src="<c:url value="/scripts/jquery-admin/jquery-ui.js" />"></script> 
 <script type="text/javascript" src="<c:url value="/scripts/jquery-admin/component.js" />"></script> 
 <script type="text/javascript" src="<c:url value="/scripts/jquery-admin/jquery-validate.js" />"></script> 
 <script type="text/javascript" src="<c:url value="/scripts/jquery-admin/jquery-form.js" />"></script> 
 <script type="text/javascript"src="<c:url value="/scripts/jquery-admin/init.js" />"></script> 
 <script type="text/javascript"src="<c:url value="/scripts/jquery-admin/jquery.ui.datepicker-zh-cn.js" />"></script> 
 <link rel="stylesheet" href="<c:url value='/styles/admin/admin1.css'/>" rel="external nofollow" > 
  <link href="<c:url value=" rel="external nofollow" rel="external nofollow" /styles/jquery-ui/jquery-ui.css" />" rel="stylesheet" type="text/css" /> 
 <script src="<c:url value="/scripts/jquery-uploadify/jquery.uploadify.min.js"/>" type="text/javascript"></script> 
 <link rel="stylesheet" type="text/css" href="<c:url value=" rel="external nofollow" rel="external nofollow" /scripts/jquery-uploadify/uploadify.css"/>"> 
  
 <style type="text/css"> 
  #jidattachtable {width:400px;font-size:14px;border:1px solid #d3d3d3;border-left-width:0;border-top-width:0;} 
  #jidattachtable td{border: 1px solid #d3d3d3;text-align:left;padding:5px;border-right-width:0;border-bottom-width:0;} 
  #jidattachtable .i-i-title{width:450px;} 
  #jidattachtable .i-i-content{width:100px;} 
 </style> 
 
 <script type="text/javascript"> 
  $(function(){ 
   //视频上传 
   var uploadvideo = $('#file_upload_video').uploadify({ 
    'buttontext':'上传视频', 
    'multi': false, 
    'filetypedesc': '请选择wmv视频文件', 
    'filetypeext': '*.wmv', 
    'swf'  : '<c:url value="/scripts/jquery-uploadify/uploadify.swf"/>"', 
    'uploader' : '<c:url value="/uploadattach.do"/>' , 
    'onuploaderror': uploadvideouploaderror, 
    'onuploadsuccess':uploadvideouploadsuccess 
   }); 
 
   function uploadvideouploaderror(){ 
    alert("上传视频发生错误"); 
   } 
 
   function uploadvideouploadsuccess(file, data, response){ 
    var strs_ = data.split("@"); 
    var videoname_ = strs_[0]; 
    var videopath_ = strs_[1]; 
 
    $("#vidiopreview").val("/upload/" + videopath_); 
 
   } 
    
   var arrattach = new array(); 
 
   //将现有的附件加载到临时数组中 
   var nowattachids_ = "${attachs}"; 
 
   //初始化现有的附件 
   if(nowattachids_ != null && nowattachids_ != ""){ 
    var ids_ = nowattachids_.split("@") ; 
    var i = 0; 
    for( ; i < ids_.length ; i++){ 
     arrattach.push(ids_[i]); 
    } 
   } 
 
   //附件上传 
   var uploadattach = $('#file_upload_attach').uploadify({ 
    'buttontext':'上传附件', 
    'multi': false, 
    'swf'  : '<c:url value="/scripts/jquery-uploadify/uploadify.swf"/>"', 
    'uploader' : '<c:url value="/uploadattach.do"/>', 
    'onuploaderror': uploadattachuploaderror, 
    'onuploadsuccess':uploadattachuploadsuccess 
   }); 
 
   function uploadattachuploaderror(){ 
    alert("上传过程中发生错误,您可以尝试重复上传一次!") 
   } 
 
   function uploadattachuploadsuccess(file, data, response){ 
 
    var strs_ = data.split("@") ; 
    var documnetid_ = strs_[0]; 
    var filename_ = strs_[1]; 
 
    var attach_ = "<tr class=\"jsclassdeleteattachbuttontr\"> " + 
      " <td class='i-i-title'>" + filename_ + "</td> " + 
      " <td class='i-i-content'><button class=\"jsclassdeleteattachbutton\" dataattach="+ documnetid_ +">删除</button></td>" + 
      " </tr>"; 
 
    arrattach.push(documnetid_); 
    $("#jidattachtable").append(attach_); 
   } 
 
   $(".jsclassdeleteattachbutton").live("click",function(){ 
 
    var data_ = $(this).attr("dataattach"); 
 
    var i_ = 0; 
    for(;i_ < arrattach.length; i_++){ 
     if(data_ == arrattach[i_]){ 
      arrattach.splice(i_,1); 
      break; 
     } 
    } 
    $(this).parent().parent().remove(); 
 
    //alert(arrattach) 
   }); 
  }); 
  
  var videotag = ""; 
 
  $(function() { 
   $("#previewdiv").dialog({ 
    title: "视频预览", 
    autoopen: false, 
    modal: true, 
    resizable: false, 
    position : "center", 
    width: "489px", 
    buttons: { 
     "关闭": function() { 
      $("#previewdiv").dialog("close"); 
 
     } 
    } 
   }); 
 
   $( "#previewdiv" ).on( "dialogopen", function( event, ui ) { 
    $("#previewdiv").html(videotag); 
   } ); 
 
   $( "#previewdiv" ).on( "dialogclose", function( event, ui ) { 
    $("#previewdiv").html(""); 
   } ); 
  }); 
  var video_root_path = "http://localhost:8080/projecttest/"; 
  function opendownloadframe() { 
   var _storepreview= video_root_path + $("#vidiopreview").val(); 
   var _embed_head = '<embed src=\"'; 
   var _embed_tail = '\" width=\"450\" height=\"400\" type=\"audio/x-wav\" loop=\"false\" autostart=\"true\">' + '</embed>'; 
    
   videotag = _embed_head + _storepreview + _embed_tail; 
 
   $("#previewdiv").dialog("open"); 
  } 
 </script> 
 </head> 
 
<body> 
 <form:form id="form" name="basedata" modelattribute="basedata" action="update.do" method="post" > 
 <div style="height:40px;border:1px solid #ebebeb;padding:10px;"> 
  <div style="width:150px;float:left;"> 
   <input id="file_upload_video" name="file_upload_video" type="file" multiple="true"> 
  </div> 
  <div style="padding-left:10px;"> 
   <input id="vidiopreview" type="text" name="${bad.attributestore}" value="${basedata[storename]}"/> 
   <input onclick="opendownloadframe();" type="button" name="button" value="预览"> 
  </div> 
 </div> 
 <div id='divcontext' style="height:40px;border:1px solid #ebebeb;padding:10px;"> 
  <div style="width:150px;float:left;"> 
   <input id="file_upload_attach" name="file_upload_attach" type="file" multiple="true"> 
  </div> 
  <div class="i-attachcontainer"> 
   <table id="jidattachtable"> 
    <c:foreach items="${attachlist}" var="attach"> 
     <tr class="jsclassdeleteattachbuttontr"> 
      <td class='i-i-title'>${attach.name}</td> 
      <td class='i-i-content'> 
       <button class="jsclassdeleteattachbutton" dataattach="${attach.id}">删除</button> 
      </td> 
      </tr> 
    </c:foreach> 
   </table> 
  </div> 
 </div> 
 <div id="previewdiv"> 
 </div> 
</form:form> 
</body> 
</html> 

后台java:

package com.sun.fileupload; 
 
import java.io.bufferedoutputstream; 
import java.io.file; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
import java.util.date; 
import java.util.iterator; 
import java.util.linkedlist; 
import java.util.list; 
 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
 
import org.apache.commons.fileupload.fileitem; 
import org.apache.commons.fileupload.fileuploadexception; 
import org.apache.commons.fileupload.disk.diskfileitemfactory; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
import org.springframework.stereotype.controller; 
import org.springframework.ui.modelmap; 
import org.springframework.web.bind.annotation.requestmapping; 
import org.springframework.web.bind.annotation.requestparam; 
import org.springframework.web.multipart.multipartfile; 
 
@controller 
public class upload{ 
 
 // 附件上传 
 @requestmapping("/uploadattach.do") 
 public void attachupload(modelmap modelmap,httpservletrequest request ,httpservletresponse response) throws ioexception { 
 
  system.out.println("upload file .... start"); 
 
  string savepath = request.getsession().getservletcontext().getrealpath("/") + "upload"; 
 
  system.out.println("store path is :" + savepath); 
 
  file f1 = new file(savepath); 
 
  if (!f1.exists()) { 
   f1.mkdirs(); 
  } 
 
  diskfileitemfactory fac = new diskfileitemfactory(); 
  servletfileupload upload = new servletfileupload(fac); 
  upload.setheaderencoding("utf-8"); 
 
  list<fileitem> filelist = null; 
  try { 
   filelist = upload.parserequest(request); 
  } catch (fileuploadexception ex) { 
   ex.printstacktrace(); 
   return; 
  } 
 
  iterator<fileitem> it = filelist.iterator(); 
  string name = ""; 
  system.out.println("deal the files ... start"); 
  //存储完毕保存进入数据库 
  //document document = null; 
  while (it.hasnext()) { 
 
   fileitem item = it.next(); 
   if (!item.isformfield()) { 
 
    name = item.getname(); 
    long size = item.getsize(); 
    string type = item.getcontenttype(); 
 
    if (name == null || name.trim().equals("")) { 
     continue; 
    } 
 
    system.out.println("dealing file info:" + "filename" + name + " size" + size + " type:" + type); 
 
    //扩展名格式: 
    if (name.lastindexof(".") >= 0) { 
     name.substring(name.lastindexof(".")); 
    } 
 
    //存文件到磁盘指定路径 且存储文件记录存入数据库,如果存储发生故障,数据库记录也会创建失败 
/*    document = new document(); 
    document.setfiletype(extname); 
    document.setfullname(name); 
    document.setdescription(name); 
    document.setname(name); 
    document.setuploaddate(new date()); 
    document = documentmanager.savewithfilestore(document,item,savepath,extname);*/ 
    system.out.println(new date() + "persist id :" + name); 
    file savefile = new file(savepath + "/" + name); 
    try { 
     item.write(savefile); 
    } catch (exception e) { 
     e.printstacktrace(); 
     throw new runtimeexception(new date() + "store file error"); 
    } 
   } 
  } 
 
  system.out.println("deal the files end"); 
  system.out.println("upload file .... end"); 
 
  response.getwriter().print(name + "@" + name); 
 } 
} 

这里把数据库更新给省略了,有需要可以自己添加。

除上传外,其他实现功能:
1. 视频上传后的预览功能
2. 视频是单文件上传,附件是多文件上传和删除

二. spring默认的上传功能:
jsp:

<%@ page contenttype="text/html;charset=utf-8" language="java" %> 
<%@ include file="../jsp/include/taglibs.jsp"%> 
 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> 
<html> 
 <head> 
 <title>upload</title> 
 <script src="<c:url value="/scripts/jquery-1.8.3.min.js"/>" type="text/javascript"></script> 
 <script type="text/javascript" src="<c:url value="/scripts/jquery-admin/jquery-ui.js" />"></script> 
  
 <link rel="stylesheet" href="<c:url value='/styles/admin/ace.css'/>" rel="external nofollow" > 
  
 <style type="text/css"> 
  .file { 
   position: relative; 
   display: inline-block; 
   background: #428bca; 
   border: 1px solid #99d3f5; 
   border-radius: 4px; 
   padding: 4px 12px; 
   overflow: hidden; 
   color: #000000; 
   text-decoration: none; 
   text-indent: 0; 
   line-height: 20px; 
  } 
  .file:link { 
   color: white; 
   text-decoration:none; 
  } 
  .file input { 
   position: absolute; 
   font-size: 100px; 
   right: 0; 
   top: 0; 
   opacity: 0; 
  } 
  .file:hover { 
   background: #1b6aaa; 
   border-color: #78c3f3; 
   color: white; 
   text-decoration: none; 
  } 
 </style> 
 
 </head> 
 
<body> 
 <form:form id="fileuploadform" method="post" action="uploadfile.do" name="uploadfile" modelattribute="uploadfile" enctype="multipart/form-data"> 
  点击保存后上传: 
  <a href="javascript:;" rel="external nofollow" class="file">选择文件 
     <input type="file" name="videofile" id="videofile"> 
  </a> 
  <input type="text" style="width:300px;" id="resourceurl-field" name="resourceurl" placeholder="资源地址" class="col-sm-12" value="${uploadfile}"/> 
  <input type="submit" value="保存" class="btn btn-sm btn-primary"> 
 </form:form> 
</body> 
</html> 

后台java:

package com.sun.fileupload; 
 
import java.io.bufferedoutputstream; 
import java.io.file; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
import java.util.date; 
import java.util.iterator; 
import java.util.linkedlist; 
import java.util.list; 
 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
 
import org.apache.commons.fileupload.fileitem; 
import org.apache.commons.fileupload.fileuploadexception; 
import org.apache.commons.fileupload.disk.diskfileitemfactory; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
import org.springframework.stereotype.controller; 
import org.springframework.ui.modelmap; 
import org.springframework.web.bind.annotation.requestmapping; 
import org.springframework.web.bind.annotation.requestparam; 
import org.springframework.web.multipart.multipartfile; 
 
@controller 
public class upload{ 
 @requestmapping(value = "/uploadfile.do") 
 public string uploadcontroller(httpservletrequest request,modelmap modelmap, 
   @requestparam("videofile") multipartfile videofile) throws illegalstateexception, ioexception{ 
  string savepath = request.getsession().getservletcontext().getrealpath("/") + "upload"; 
   
  try { 
   uploadsinglefile(savepath, videofile, request.getsession().getservletcontext().getrealpath("/")); 
  }catch (exception e) { 
   return "/upload"; 
  } 
 
  modelmap.addattribute("uploadfile", "upload/" + videofile.getoriginalfilename()); 
   
  return "/upload"; 
 }  
 
 /** 
  * 
  * @param path 这个path 是upload的子目录路径 比如 path=/image 最终将下载到[root/upload/image/]目录下 
  * @param file 
  * @return 
  * @throws java.io.ioexception 
  */ 
 public static string uploadsinglefile(string path, multipartfile file, string rootpath) { 
   
  if (!file.isempty()) { 
    
    byte[] bytes; 
    try { 
     bytes = file.getbytes(); 
     
     // create the file on server 
     file serverfile = new file(path + "/" + file.getoriginalfilename()); 
     bufferedoutputstream stream = new bufferedoutputstream(new fileoutputstream(serverfile)); 
     stream.write(bytes); 
     stream.close(); 
  
     system.out.println("server file location=" + serverfile.getabsolutepath()); 
 
     return getrelativepathfromuploaddir(serverfile, rootpath).replaceall("\\\\", "/"); 
    } catch (ioexception e) { 
     e.printstacktrace(); 
    } 
    
  }else{ 
   system.out.println("文件内容为空"); 
  } 
  return null;  
 } 
  
 /** 
  * 
  * @param file 
  * @return 返回从upload目录下面的相对路径 
  */ 
 public static string getrelativepathfromuploaddir(file file, string rootpath){ 
  if(null==file) 
   return ""; 
  string absolutepath = file.getabsolutepath(); 
  if(absolutepath.indexof(rootpath)!=-1 && rootpath.length()<absolutepath.length()) 
   return absolutepath.substring(absolutepath.indexof(rootpath)+rootpath.length()); 
  else 
   return ""; 
 } 
} 

spring配置文件springmvc-servlet.xml中添加:

<bean id=”multipartresolver” class=”org.springframework.web.multipart.commons.commonsmultipartresolver”> 
<property name=”defaultencoding” value=”utf-8″ /> 
</bean> 

如果和uploadify同时使用的话,需要做一些修改,否则uploadify的上传文件会被spring拦截:

 <!-- 支持上传文件 --> 
lt;bean id="multipartresolver" class="org.sun.com.mymultipartresolver"> 
 <!--设置上传文件的编码格式,用于解决上传的文件中文名乱码问题 --> 
 <property name="defaultencoding"> 
  <value>utf-8</value> 
 </property> 
<property name="excludeurls" value="/uploadattach.do,/uploadvideo.do"/> 
lt;/bean> 

org.sun.com.mymultipartresolver: 

package org.sun.com; 
 
import javax.servlet.http.httpservletrequest; 
 
import org.springframework.web.multipart.commons.commonsmultipartresolver; 
 
/** 
 * @author sun 
 */ 
public class mymultipartresolver extends commonsmultipartresolver { 
 private string excludeurls;  
 private string[] excludeurlarray; 
  
 public string getexcludeurls() { 
  return excludeurls; 
 } 
 
 public void setexcludeurls(string excludeurls) { 
  this.excludeurls = excludeurls; 
  this.excludeurlarray = excludeurls.split(","); 
 } 
 
 /** 
  * 这里是处理multipart http的方法。如果这个返回值为true,那么multipart http body就会mymultipartresolver 消耗掉.如果这里返回false 
  * 那么就会交给后面的自己写的处理函数处理例如刚才servletfileupload 所在的函数 
  * @see org.springframework.web.multipart.commons.commonsmultipartresolver#ismultipart(javax.servlet.http.httpservletrequest) 
  */ 
 @override 
 public boolean ismultipart(httpservletrequest request) { 
  for (string url: excludeurlarray) { 
   // 这里可以自己换判断 
   if (request.getrequesturi().contains(url)) { 
    return false; 
   } 
  } 
   
  return super.ismultipart(request); 
 } 
  
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。