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

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

一. uploadify:

uploadify控件的scripts和styles在这里:图片上传

JSP:

<%@ page contentType="text/html;charset=UTF-8" language="java" %> 
<%@ include file="../jsp/include/taglibs.jsp"%> 
 
 
 
  
 Upload 
  
  
  
  
  
  
  
  
  " rel="stylesheet" type="text/css" /> 
  
 "> 
  
  
 
  
  
 
 
  
 
${attach.name}

后台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 fileList = null; 
  try { 
   fileList = upload.parseRequest(request); 
  } catch (FileUploadException ex) { 
   ex.printStackTrace(); 
   return; 
  } 
 
  Iterator 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"%> 
 
 
 
  
 Upload 
  
  
  
  
  
  
 
  
 
 
  
  点击保存后上传: 
  选择文件 
      
   
   
   
  
 
 

后台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() 
 

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

 
 
 

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

  
lt;bean id="multipartResolver" class="org.sun.com.MyMultipartResolver"> 
  
  
  UTF-8 
  
 
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); 
 } 
  
} 

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

你可能感兴趣的:(Java实现文件上传的两种方法(uploadify和Spring))