首页 > 编程语言 > 详细

springMVC(六)——文件上传

时间:2019-09-04 22:12:28      阅读:67      评论:0      收藏:0      [点我收藏+]

SpringMVC文件的上传

直接来步骤和代码:

1、首先需要导入jar包

技术分享图片

2、前端代码

加颜色的代码需要注意

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        姓名:<input type="text" name="name"/><br>
        年龄:<input type="text" name="age"/><br>
        请选择上传文件:<input type="file" name="multipartFile"/>
        <input type="submit" value="上传">
    </form>
</body>
</html>

 

3、在springmvc中配置文件上传解析器

<!-- 配置文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置文件上传的大小  字节  -->
        <property name="maxUploadSize" value="20971520"></property>
    </bean>

 

4、控制层处理代码

@Controller
public class TestController {
    @RequestMapping("upload")
    //HttpServletRequest:作用是为了获取上传文件的路径
    public String uploadFiles(MultipartFile multipartFile,HttpServletRequest request,Student stu,Model model) {
        //获取文件上传真实保存路径
        String path = request.getServletContext().getRealPath("/upload");
        System.out.println(path);
        //创建一个对象
        File file = new File(path);
        if(!file.exists()) {//该路径不存在
            file.mkdirs();
        }
        //获取文件名
        String filename =System.currentTimeMillis()+ multipartFile.getOriginalFilename();
        System.out.println(filename);
        File targetfile = new File(path+"/"+filename);
        try {
            //把文件写到指定的目录下
            FileUtils.writeByteArrayToFile(targetfile, multipartFile.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        stu.setImgname(filename);
        model.addAttribute("stu", stu);
        return "info";
        
    }
}

 

springMVC(六)——文件上传

原文:https://www.cnblogs.com/zjc364259451/p/11461590.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!