栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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" /> 
  
 "> 
  
  
  #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;} 
  
 
  
  
 
 
  
  
   
    
   
   
    
    
   
  
  
   
    
   
   
    
     
${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(".")); 
    } 
 
    //存文件到磁盘指定路径 且存储文件记录存入数据库,如果存储发生故障,数据库记录也会创建失败 
 
    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 
  
  
  
  
  
  
  .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; 
  } 
  
 
  
 
 
  
  点击保存后上传: 
  选择文件 
      
   
   
   
  
 
 

后台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"; 
 }  
 
  
 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;  
 } 
  
  
 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; 
 
 
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(","); 
 } 
 
  
 @Override 
 public boolean isMultipart(HttpServletRequest request) { 
  for (String url: excludeUrlArray) { 
   // 这里可以自己换判断 
   if (request.getRequestURI().contains(url)) { 
    return false; 
   } 
  } 
   
  return super.isMultipart(request); 
 } 
  
} 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/143125.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号