zoukankan      html  css  js  c++  java
  • springMVC文件上传

    1. 引入Jar包

    commons-fileupload-1.2.2.jar

    commons-io-2.1.jar


    2.user-servlet.xml中配置文件上传

    <!-- 配置文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<property name="maxUploadSize" value="5000000"></property>
    </bean>
    3. UserController.java

    @Controller
    @RequestMapping("/user")
    public class UserController {
    	// 使用map模拟数据库 
    	private Map<String, User> userMap = new HashMap<String, User>();
    
    	public UserController() {
    		userMap.put("zhangsan", new User("zhangsan", "123"));
    		userMap.put("lishimin", new User("lishimin", "456"));
    	}
    	
    	// 文件上传
    	// 訪问方法: http://localhost/springmvc_user/upload.jsp
    	@RequestMapping(value="/upload",method=RequestMethod.POST)
    	public String upload(@RequestParam("attachs")MultipartFile[] attachs,HttpServletRequest req) throws IOException {
    		String realpath = req.getSession().getServletContext().getRealPath("/resources/upload");
    		System.out.println(realpath);
    		for(MultipartFile attach:attachs) {
    			if(attach.isEmpty()){
    				continue;
    			}
    			File file = new File(realpath + "/" + attach.getOriginalFilename()); 
    			FileUtils.copyInputStreamToFile(attach.getInputStream(),file);
    		}
    		return "success";
    	}
    	
    }
    4. 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>
    <form method="post" action="user/upload" enctype="multipart/form-data">
    	Attach:<br/>
        <input type="file" name="attachs"/><br/>	
        <input type="file" name="attachs"/><br/>	
        <input type="file" name="attachs"/><br/>	
        <input type="submit" value="上传文件"/>
    </form>
    </body>
    </html>

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    【Statistics】均值
    【Datastage】在win10安装Datastge 8.7
    【Linux】行首、行尾添加字符串
    【Linux】替换文本中的字符
    【Pyhton 数据分析】通过gensim进行文本相似度分析
    【Python 数据分析】jieba文本挖掘
    异或运算法则
    关于计算机中的《补码》,公式:-n=~n+1 引伸:~n=-n-1
    Base64编码解码
    位运算之——按位与(&)操作——(快速取模算法)
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4725476.html
Copyright © 2011-2022 走看看