这篇文章是介绍文件上传的,由于在spring MVC上实现起来和直接在servlet中写有些不同,所以特地写了一下这篇文章,关于不同点,大家可以先阅读一下上一篇文章。好了,下面直接上代码。

jab包是jspSmartUpload.jar,如果有类似的jar包如:commons-fileupload-1.2.2,留一个即可,否则会冲突报错

首先是一个简单的页面(jsp),比较丑,但能用:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="pragma" content="no-cache" />
<base target="_self">
<title>文件上传</title>
</head>
<body>
<h5>文件上传</h5><hr/>
<form id="uploadForm" action="http://localhost:8080/springMVC/fileLoad/upload.do" enctype="multipart/form-data" method="post">
<div><input type="file" size="25" maxlength="80" name="file_upload"/></div>
<div><input type="submit" value="上传"/></div>
</form>
</body>
</html>

效果图:

然后是controller代码,至于为什么这样写,可以参考上一篇文章:

package module.system.controller;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import module.system.common.FileLoad; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletConfigAware;
import org.springframework.web.context.ServletContextAware;
/**
* 文件上传下载.
*
*/
@Controller
@RequestMapping("/fileLoad")
public class FileLoadController implements ServletConfigAware,ServletContextAware{ private ServletContext servletContext;
@Override
public void setServletContext(ServletContext arg0) {
this.servletContext = arg0;
}
private ServletConfig servletConfig;
@Override
public void setServletConfig(ServletConfig arg0) {
this.servletConfig = arg0;
} @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
@ResponseBody //此注解表明返回值跳过视图处理部分,直接写入 http response body中
public String upload(HttpServletRequest request,HttpServletResponse response) { FileLoad fileLoad = new FileLoad();
try {
fileLoad.upload(request, response,servletConfig);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
} }

接着是FileLoad类:

package module.system.common;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random; import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.SmartFile;
import com.jspsmart.upload.SmartUpload; /**
* 文件上传下载.
* @author nagsh.
*
*/
public class FileLoad{ /**
* 文件上传.
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String upload(HttpServletRequest request, HttpServletResponse response,ServletConfig config) throws ServletException, IOException { request.setCharacterEncoding("utf-8");
//新建一个SmartUpload对象
SmartUpload mySmartUpload=new SmartUpload();
String fileId = "";
try{
//上传初始化
mySmartUpload.initialize(config, request, response);
//设定每个上传文件的最大长度
mySmartUpload.setMaxFileSize(1*512*1024);
//设定总上传数据的长度
mySmartUpload.setTotalMaxFileSize(1*1024*1024);
//设定允许上传的文件的类型,只允许上传java,doc,txt文件
mySmartUpload.setAllowedFilesList("java,doc,txt");
//设定禁止上传的文件的类型,禁止上传带有exe,bat文件
mySmartUpload.setDeniedFilesList("exe,bat");
//上传文件
mySmartUpload.upload(); //处理每个上传文件
for(int i=0;i<mySmartUpload.getFiles().getCount();i++)
{
SmartFile file=mySmartUpload.getFiles().getFile(i);
//判断用户是否选择了文件
if(!file.isMissing()){
//另存到以Web应用程序的根目录为文件根目录的目录下
//(声明一下:在Myeclipse中,该目录位于工程下的.metadata/.me_tcat/webapps/该工程目录/upload/)
//生成唯一的文件索引(日期+两个随机数)
String fileName =file.getFileName();
String data[] = fileName.split("\\.");
System.out.println(data.length);
String fileType = data[1]; //文件类型
System.out.println(fileType);
Date now = new Date();
DateFormat YMD = new SimpleDateFormat("yyyyMMdd");//年-月-日
String ymd = YMD.format(now);//当前年-月-日
Random random = new Random();
int r1 = random.nextInt(99999);
int r2 = random.nextInt(99999);
fileId = ymd+r1+""+r2;
System.out.println(fileId);
file.saveAs("/upload/"+fileId+"."+fileType,mySmartUpload.SAVE_VIRTUAL);
}
}
}catch(Exception e){//异常处理
//打印自定义异常信息
}
return fileId;
} public static void main(String[] args) { } }

测试时写一个按钮,点击后弹出上面那个页面就行。

文件上传后的名字是随机生成的,这块可以根据实际情况改,代码中写明白了。

还要强调的是我写的这个例子文件是上传到tomcat/webapps/项目/upload下,所以需要先在tomcat下创建一个文件夹。

版权声明:本文为博主原创文章,未经博主允许不得转载。

文件上传--基于Spring MVC框架+SmartUpload的更多相关文章

  1. web大文件上传(web应用---SSH框架)

    版权所有 2009-2018荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webapp/up6.2/in ...

  2. java文件上传--基于ajaxFileUpload+struts2

    jQuery插件ajaxFileUpload可以实现ajax文件上传,使用非常简单. 下面做一个简单的demo(以上传图片为例),实现图片上传,图片显示,图片下载 注:以下的代码是在项目的基础上进行开 ...

  3. flash上传在spring mvc中出现的问题2

    转载请注明: TheViper http://www.cnblogs.com/TheViper  这两天本屌在做flash拼图上传遇到点坑 上传原理很简单,就是把上图右边画布区域BitmapData. ...

  4. SpringMVC常用配置-文件上传-基于Servlet 3.0

    [2] http://www.cnblogs.com/weilu2/p/springmvc_MultipartConfigElement_tomcat_webapps_work.html

  5. Android 文件上传 使用AsyncHttpClient开源框架

    public void upload(View view) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams reques ...

  6. Spring MVC 学习总结(五)——校验与文件上传

    Spring MVC不仅是在架构上改变了项目,使代码变得可复用.可维护与可扩展,其实在功能上也加强了不少. 验证与文件上传是许多项目中不可缺少的一部分.在项目中验证非常重要,首先是安全性考虑,如防止注 ...

  7. Spring MVC-学习笔记(5)spring MVC的文件上传、下载、拦截器

    1.文件上传.      spring MVC为文件上传提供了直接的支持,这种支持是即插即用的MultipartResolver(多部分解析器)实现的.spring MVC使用Apache Commo ...

  8. 从.Net到Java学习第十篇——Spring Boot文件上传和下载

    从.Net到Java学习系列目录 图片上传 Spring Boot中的文件上传就是Spring MVC中的文件上传,将其集成进来了. 在模板目录创建一个新的页面 profile/uploadPage. ...

  9. Spring Boot 文件上传原理

    首先我们要知道什么是Spring Boot,这里简单说一下,Spring Boot可以看作是一个框架中的框架--->集成了各种框架,像security.jpa.data.cloud等等,它无须关 ...

随机推荐

  1. Android实训案例(五)——四大组件之一ContentProvider的使用,通讯录的实现以及ListView的优化

    Android实训案例(五)--四大组件之一ContentProvider的使用,通讯录的实现 Android四大组件是啥这里就不用多说了,看图吧,他们之间通过intent通讯 我们后续也会一一的为大 ...

  2. HBase中创建索引

    hbasene(https://github.com/akkumar/hbasene)是开源项目,在hbase存储上封装使用Lucene来创建索引,代码API非常简单,熟悉lucene的朋友可以很方便 ...

  3. LeetCode之旅(17)-Ugly Number

    题目: Write a program to check whether a given number is an ugly number. Ugly numbers are positive num ...

  4. fastDFS与java整合文件上传下载

    准备 下载fastdfs-client-java源码 源码地址 密码:s3sw 修改pom.xml 第一个plugins是必需要的,是maven用来编译的插件,第二个是maven打源码包的,可以不要. ...

  5. 检查Json格式工具

    在线JSON校验格式化工具(Be JSON) 地址:http://www.bejson.com/

  6. Js 实现自定义事件

    var Event = { on: function (eventName, callback) { if (!this[eventName]) { this[eventName] = []; } t ...

  7. Android集成ffmpeg

    1.ffmpeg官网文档地址:https://trac.ffmpeg.org/wiki/CompilationGuide/Android 2.上面页面资源列表里面第一项 https://github. ...

  8. No module named zope.interface error的解决

    明明安装了 zope.interface,还是出现标题错误,错误语句是 from zope.interface import ooxx 根据 http://stackoverflow.com/ques ...

  9. SOFA 源码分析 —— 过滤器设计

    前言 通常 Web 服务器在处理请求时,都会使用过滤器模式,无论是 Tomcat ,还是 Netty,过滤器的好处是能够将处理的流程进行分离和解耦,比如一个 Http 请求进入服务器,可能需要解析 h ...

  10. spring+spring mvc+mybatis 实现主从数据库配置

    一.配置文件 1.jdbc.properties master_driverUrl=jdbc:mysql://localhost:3306/shiro?useUnicode=true&char ...