代码&优雅着&生活

导航

spring mvc 文件上传工具类

虽然文件上传在框架中,已经不是什么困难的事情了,但自己还是开发了一个文件上传工具类,是基于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文件上传工具完毕。

 

posted on 2015-08-12 12:26  幸运的凌人  阅读(1143)  评论(0编辑  收藏  举报