SSM网页上传文件

效果:

需要的资源:

       commons-fileupload-1.3.1.jar,commons-io-1.3.2.jar

步骤:

       1:搭建SSM框架:

       2:在配置文件springconfig.xml中添加配置

        

	<!-- 定义文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880" />
        <property name="maxInMemorySize" value="4096" />
    </bean>

       3:编写上传jsp文件:upload.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">
<title>上传文件</title>
</head>
<body>
<h1>文件上传实例</h1>
<form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload.action" >
    <a>选择一个文件:</a>
    <input type="file" name="file" /><br/>
    <input type="submit" value="上传" />
</form>
</body>
</html>

 

       4:编辑控制器

    /**
     * 文件上传功能
     * @param file
     * @return
     * @throws IOException 
     */
    @RequestMapping(value="/upload",method=RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
    	String fileMsg = UploadFileMsg(request);
    	System.out.println("fileMsg:"+fileMsg);
        String path = request.getSession().getServletContext().getRealPath("upload");//目录
        String fileName = file.getOriginalFilename();//文件名
        System.out.println("path:"+path);
        System.out.println("fileName:"+fileName);
        File dir = new File(path,fileName);        
        if(!dir.exists()){//如果目录不存在,则创建
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);//下载文件
    	System.out.println("ok");
        return "success";
    }

       5:运行,成功的话页面信息如下,且对应目录下有文件信息

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值