虽然文件上传在框架中,已经不是什么困难的事情了,但自己还是开发了一个文件上传工具类,是基于springmvc文件上传的。

工具类只需要传入需要的两个参数,就可以上传到任何想要上传的路径:

参数1:HttpServletRequest request

参数2:String storePath   //文件存储相对路径 ,例如:"/upload","/image","/local/file"

返回值:上传到服务器的相对路径

一:代码实现

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver; public class FileUploadUtils {
/**
*
* @param request
* @param storePath 文件存储相对路径 ,例如:"/upload","/image","/local/file"
* @return
*/
public static String tranferFile(HttpServletRequest request,String storePath){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//先判断request中是否包涵multipart类型的数据,
if(multipartResolver.isMultipart(request)){
//再将request中的数据转化成multipart类型的数据
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iter = multiRequest.getFileNames();
while(iter.hasNext()){
MultipartFile file = multiRequest.getFile((String)iter.next());
if(file != null){
String originalFileName = file.getOriginalFilename(); String path =request.getSession().getServletContext().getRealPath(storePath);
//得到存储到本地的文件名
String localFileName=UUID.randomUUID().toString()+getFileSuffix(originalFileName);
//新建本地文件
File localFile = new File(path,localFileName);
            //创建目录
File fileDir=new File(path);
                    if (!fileDir.isDirectory()) {
                        // 如果目录不存在,则创建目录
                        fileDir.mkdirs();
                    } String src=storePath+"/"+localFileName;
//写文件到本地
try {
file.transferTo(localFile);
return src;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
/**
* 获取文件后缀
* @param originalFileName
* @return
*/
public static String getFileSuffix(String originalFileName){
int dot=originalFileName.lastIndexOf('.');
if((dot>-1)&&(dot<originalFileName.length())){
return originalFileName.substring(dot);
}
return originalFileName;
}
}

二:controller 调用

@Controller
@RequestMapping("/file")
public class FileUploadController { @RequestMapping("save")
@ResponseBody
public String save(String name,String password,HttpServletRequest request,HttpServletResponse response){
System.out.println("name-----------------------"+name);
System.out.println("password-----------------------"+password);return FileUploadUtils.tranferFile(request, "/upload");
}
}

三:jsp页面代码

<h2>文件上传</h2>
<form name="upload" action="/file/save" enctype="multipart/form-data" method="post">
  姓名:<input name="name" type="text">
  密码:<input name="password" type="text">
  文件:<input type="file" name="thefile" />
  <input type="submit" value="上传文件" />
</form>

四:springmvc配置文件中, 配置文件上传视图支持

<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="20000000"></property>
</bean>

至此,一个完整的springmvc文件上传工具完毕。

spring mvc 文件上传工具类的更多相关文章

  1. spring boot 文件上传工具类(bug 已修改)

    以前的文件上传都是之前前辈写的,现在自己来写一个,大家可以看看,有什么问题可以在评论中提出来. 写的这个文件上传是在spring boot 2.0中测试的,测试了,可以正常上传,下面贴代码 第一步:引 ...

  2. Spring MVC 笔记 —— Spring MVC 文件上传

    文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...

  3. 【Java Web开发学习】Spring MVC文件上传

    [Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...

  4. 文件上传工具类 UploadUtil.java

    package com.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  5. FastDFS 文件上传工具类

    FastDFS文件上传工具类 import org.csource.common.NameValuePair; import org.csource.fastdfs.ClientGlobal; imp ...

  6. Spring MVC文件上传教程 commons-io/commons-uploadfile

    Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...

  7. Spring mvc文件上传实现

    Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...

  8. Spring mvc 文件上传到文件夹(转载+心得)

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  9. spring mvc 文件上传 ajax 异步上传

    异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...

随机推荐

  1. (转)css选择器及其优先级

    文章主要介绍什么是CSS选择器,CSS选择器的分类以及CSS选择器的优先级三部分内容,希望能够帮助到正在学习CSS的童鞋,有什么不足的地方欢迎大家批评指正. 一.什么是CSS选择器? CSS选择器又被 ...

  2. HW3 纠结的心得

    改好的controller //yuec2 Yue Cheng package hw3; import java.io.File; import java.text.DecimalFormat; im ...

  3. [leetcode]300. Longest Increasing Subsequence最长递增子序列

    Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Inp ...

  4. 13-算法训练 P0505

    算法训练 P0505   时间限制:1.0s   内存限制:256.0MB      一个整数n的阶乘可以写成n!,它表示从1到n这n个整数的乘积.阶乘的增长速度非常快,例如,13!就已经比较大了,已 ...

  5. 关于vue的npm run dev和npm run build

    ├─build │ ├─build.js │ ├─check-versions.js │ ├─dev-client.js │ ├─dev-server.js │ ├─utils.js │ ├─vue- ...

  6. golang 实现延迟消息原理与方法

    实现延迟消息具体思路我是看的下面这篇文章 https://mp.weixin.qq.com/s/eDMV25YqCPYjxQG-dvqSqQ 实现延迟消息最主要的两个结构: 环形队列:通过golang ...

  7. Liunx cp

    功能: 复制文件或目录 使用权限:所有使用者说明: cp指令用于复制文件或目录,如同时指定两个以上的文件或目录,且最后的目的地是一个已经存在的目录,则它会把前面指定的所有文件或目录复制到此目录中.若同 ...

  8. Ubuntu 软件包管理工具 dpkg, APT 的一些命令(转载)

    转载地址: http://www.dreamxu.com/ubuntu-package-dpkg-and-apt-commands/ dpkg dpkg 是由 Debian 开发的包管理系统,是一个比 ...

  9. java基础之—类加载器

    要了解类加载器先要了解类的加载 一.类的加载(类的加载概述) 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三步来实现对这个类进行初始化. 1.加载 就是指将clas ...

  10. iOS.CocoaPods.0

    1. CocoaPods CocoaPods 是Objective-C (iOS and OS X) projects 的依赖管理器. A CocoaPod (singular) is a speci ...