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

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

一. 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);
 } 

}

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

(0)

相关推荐

  • jquery.form.js框架实现文件上传功能案例解析(springmvc)

    上一篇 Bootstrap自定义文件上传下载样式(http://www.jb51.net/article/85156.htm)已经有一段时间了,一直在考虑怎么样给大家提交一篇完美的逻辑处理功能.现在我结合自己的实际工作给大家分享一下. 使用的技术有jquery.form.js框架, 以及springmvc框架.主要实现异步文件上传的同时封装对象,以及一些注意事项. 功能本身是很简单的,但是涉及到一些传递参数类型的问题.例如:jquery的ajax方法与jquery.form.js中的ajaxSu

  • Java Spring MVC 上传下载文件配置及controller方法详解

    下载: 1.在spring-mvc中配置(用于100M以下的文件下载) <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!--配置下载返回类型--> <bean class="or

  • 详解SpringBoot文件上传下载和多文件上传(图文)

    最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码: 1.开发环境: IDEA15+ Maven+JDK1.8 2.新建一个maven工程: 3.工程框架 4.pom.xml文件依赖项 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

  • Spring实现文件上传(示例代码)

    在实际开发中,经常遇到要实现文件上传到服务器端的功能.Spring可以继承commons-fileupload插件来实现文件上传的功能.分为前端JSP编写和后台Controller的编写. 前期准备工作,首先要引入commons-fileupload这个jar包,pom.xml中的配置如下: 复制代码 代码如下: <!-- 实现文件上传,spring集成了这个功能 --><dependency> <groupId>commons-fileupload</group

  • SpringMVC文件上传 多文件上传实例

    必须明确告诉DispatcherServlet如何处理MultipartRequest.SpringMVC中提供了文件上传使用方式如下配置xxx-servlet.xml,添加如下代码: 复制代码 代码如下: <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          <!-- 设置

  • SpringMVC 文件上传配置,多文件上传,使用的MultipartFile的实例

    基本的SpringMVC的搭建在我的上一篇文章里已经写过了,这篇文章主要说明一下如何使用SpringMVC进行表单上的文件上传以及多个文件同时上传的步骤 文件上传项目的源码下载地址:demo 一.配置文件: SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver:用于处理表单中的file <!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver -->

  • uploadify java实现多文件上传和预览

    本文实例为大家分享了java文件上传和预览实现代码,供大家参考,具体内容如下 1.下载uploadify插件 2.index.html <!DOCTYPE html> <html lang="en"> <head> <@head/> <script src="<@path/>/js/uploadify-v3.1/jquery.uploadify-3.1.js"></script> &

  • SpringMVC上传图片与访问

    关于springmvc上传图片的方法小编给大家整理了两种方法,具体内容如下所示: 第一种:(放在该项目下的物理地址对应的位置) a. 路径写法: String basePath="/WEB-INF/resources/upload"; String filePathName= request.getSession().getServletContext().getRealPath(basePath);存放路径 b. 实际路径: D:\WorkSpace\.metadata\.plugi

  • 详解SpringMVC使用MultipartFile实现文件的上传

    如果需要实现跨服务器上传文件,就是将我们本地的文件上传到资源服务器上,比较好的办法就是通过ftp上传.这里是结合SpringMVC+ftp的形式上传的.我们需要先懂得如何配置springMVC,然后在配置ftp,最后再结合MultipartFile上传文件. springMVC上传需要几个关键jar包,spring以及关联包可以自己配置,这里主要说明关键的jar包 1:spring-web-3.2.9.RELEASE.jar (spring的关键jar包,版本可以自己选择) 2:commons-

  • Spring MVC中上传文件实例

    SpringMVC(注解)上传文件需要注意的几个地方: 1.form的enctype="multipart/form-data",这个是上传文件必须的 2.applicationContext.xml配置: 复制代码 代码如下: <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.w

随机推荐