SSM接收前端file文件

如何获取前台传来的file类型文件

利用@RequestParam(value = “传来的文件名”,required = false)MultipartFile multipartFile来解析;
这样操作会破坏spring的自动封装实体类,不能直接一个user类来接收前台的所有传参了;
通过multipartFile.getInputStream()方法将文件转换成InputStream流;

 @RequestMapping(value = "/insert",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView insert(@RequestParam(value = "bookimg",required = false)MultipartFile multipartFile,
                               HttpServletRequest request,
                               HttpServletResponse response,
                               String bookname,
                               String bookintro,
                               String booktype,
                               String bookcon,
                               String bookwriter, HttpSession session, ModelAndView mv)throws IllegalStateException, IOException

mvc.xml配置

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="512895771"/>
    </bean>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SSM(Spring + SpringMVC + MyBatis)是一种常用的Java Web开发框架组合,下面是一个基本的SSM实现文件上传的示例: 1. 首先,在Spring配置文件中添加以下配置: ``` <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5242880"/> <!-- 设置最大上传文件大小 --> </bean> ``` 2. 在Controller中添加处理文件上传的方法: ```java @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { // 获取文件名 String fileName = file.getOriginalFilename(); // 设置文件存储路径 String filePath = "C:/uploads/" + fileName; // 创建文件对象 File dest = new File(filePath); // 检查目标目录是否存在,不存在则创建 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } // 将文件写入目标目录 file.transferTo(dest); return "upload success"; } catch (IOException e) { e.printStackTrace(); return "upload failed"; } } else { return "file is empty"; } } ``` 3. 在前端页面中添加上传文件的表单: ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="Upload" /> </form> ``` 当用户选择文件并提交表单时,控制器方法会接收文件并将其保存到指定的目录中。请确保文件上传目录存在并有足够的权限。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值