springmvc 单个文件上传

本文介绍了一个使用SpringMVC实现文件上传的例子,包括前端表单设计、后端控制器处理逻辑、配置文件设置及结果展示页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、前台页面

<form name="uploadFile2" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload/uploadFile3.do">
 	<label>文件名称:</label>
 	<input type="text" name="userName3">
 	<input type="file" name="fileupload3"/>
 	<input type="submit" value="提交2"/>
 </form>

前台采用form表单同步提交方式。

二、在web-info下建立上传文件夹upload

三、后台java

    @RequestMapping(value="uploadFile3.do")
    public String uploadFile3(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="fileupload3") MultipartFile file, ModelMap map) {
    	String userName = request.getParameter("userName3");
    	System.out.println("userName:"+userName);
    	if(!file.isEmpty()) {
            //上传文件路径
            String path = request.getSession().getServletContext().getRealPath("/upload/");
            //上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path,filename);
            //判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) { 
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            try {
				file.transferTo(new File(path + File.separator + filename));
				map.addAttribute("message", "上传成功哈哈");
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				map.addAttribute("message", "上传异常");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				map.addAttribute("message", "上传异常");
			}
        } else {
        	map.addAttribute("message", "参数异常");
        }
    	return "message";
    }

四、springmvc.xml配置文件加入配置信息

<bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 上传文件大小上限,单位为字节(10MB) -->
        <property name="maxUploadSize">  
            <value>10485760</value>  
        </property>  
        <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
</bean>

五、建立message.jsp页面:

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
 <title>消息提示</title>
</head>
 
<body>
  ${message}
</body>
</html>


tomcat下上传实际路径通过打印可知:D:\testPro\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\mySSM2\upload



参考文章:http://www.cnblogs.com/WJ-163/p/6269409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值