关于上传文件的问题

关于上传文件的问题

如果在jsp页面使用了springmvc表单,向controller上传参数(通过modelAttribute),同时还要上传文件,该如何处理呢?比如课程中报销单创建时需要提交差旅票据扫描件上传,类似这样的应用场景

正在回答

登陆购买课程后可参与讨论,去登陆

4回答

同学你好,pom文件中的依赖有如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
        </dependency>
    </dependencies>

祝:学习愉快~

  • 慕沐8221787 提问者 #1
    controller中的方法参数能按如下写吗? public String addGoods(@RequestParam("goods") Goods goods, @RequestParam("path") MultipartFile path, HttpServletRequest request) {}
    2020-05-11 07:59:40
  • 好帮手慕阿满 回复 提问者 慕沐8221787 #2
    不可以的。祝:学习愉快~
    2020-05-11 13:45:44
好帮手慕阿满 2020-05-10 14:36:26

同学你好,如下给出一种SpringMVC使用form表单上传文件:

实体类Goods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class Goods {
    private String goodsId;
    private String goodsName;
    private String path;
    private int price;
    private String desc;
 
    public Goods(String goodsId, String goodsName, String path, int price, String desc) {
        this.goodsId = goodsId;
        this.goodsName = goodsName;
        this.path = path;
        this.price = price;
        this.desc = desc;
    }
 
    public Goods() {
    }
 
    public String getGoodsId() {
        return goodsId;
    }
 
    public void setGoodsId(String goodsId) {
        this.goodsId = goodsId;
    }
 
    public String getGoodsName() {
        return goodsName;
    }
 
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
 
    public String getPath() {
        return path;
    }
 
    public void setPath(String path) {
        this.path = path;
    }
 
    public float getPrice() {
        return price;
    }
 
    public void setPrice(int price) {
        this.price = price;
    }
 
    public String getDesc() {
        return desc;
    }
 
    public void setDesc(String desc) {
        this.desc = desc;
    }
 
    @Override
    public String toString() {
        return "Goods{" +
                "goodsId='" + goodsId + '\'' +
                ", goodsName='" + goodsName + '\'' +
                ", path='" + path + '\'' +
                ", price=" + price +
                ", desc='" + desc + '\'' +
                '}';
    }
}

配置文件applicatiocontext.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
   
 
    <mvc:annotation-driven />
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
        <property name="maxUploadSize">
            <value>32505856</value>
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>
</beans>

控制器类GoodsController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import com.imooc.entity.Goods;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
 
@Controller
public class GoodsController {
    @GetMapping("/toadd")
    public String toAdd(){
        return "addGoods";
    }
 
    @PostMapping("/addGoods")
    public String addGoods(@RequestParam("goodsId") String goodsId, @RequestParam("goodsName") String goodsName,
                             @RequestParam("path") MultipartFile path, @RequestParam("price") String price,
                             @RequestParam("desc") String desc, HttpServletRequest request) {
        Goods goods = new Goods();
        goods.setGoodsId(goodsId);
        goods.setGoodsName(goodsName);
        goods.setPrice(Integer.valueOf(price));
        goods.setDesc(desc);
        // 判断文件是否存在
        if (!path.isEmpty()) {
            // 循环输出上传文件
            // 获取原始的文件名称
            String originalFilename = path.getOriginalFilename();
            // 设置上传文件的保存目录
            String uploadPath = request.getServletContext().getRealPath("/upload/");
            File filePath = new File(uploadPath);
            System.out.println(uploadPath);
            if (!filePath.exists()) {
                // 如果目录不存在就创建
                filePath.mkdir();
            }
            String newFileName = getRandomFileName() + "_" + originalFilename;
            try {
                path.transferTo(new File(filePath + "\\" + newFileName));
                System.out.println(filePath + "\\" + newFileName);
            catch (IOException e) {
                e.printStackTrace();
            }
            goods.setPath(filePath + "\\" + newFileName);
        }
        System.out.println(goods);
        return "success";
    }
 
 
    public static String getRandomFileName() {
        Random r = new Random();
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        // 获取随机的五位数
        int rannum = r.nextInt(89999) + 10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return nowTimeStr + rannum;
    }
 
}

添加商品的jsp页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/addGoods" method="post" enctype="multipart/form-data">
        商品Id:  <input type="text" name="goodsId" id="goodsId"><br/>
        商品名称: <input type="text" name="goodsName" id="goodsName"><br/>
        商品图片:<input type="file" name="path" id="path"><br/>
        商品价格:<input type="text" name="price" id="price"><br/>
        商品描述:<input type="text" name="desc" id="desc"><br/>
    <input type="submit" value="提交">
    </form>
 
</body>
</html>

web.xml配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<web-app>
  <display-name>Archetype Created Web Application</display-name>
 
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationcontext.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

项目结构:

http://img1.sycdn.imooc.com//climg/5eb7a0bb0930310604080674.jpg

添加商品后,target目录下的upload会出现上传的文件。

祝:学习愉快~

  • 提问者 慕沐8221787 #1
    pom.xml文件需要添加什么依赖?
    2020-05-10 16:04:05
好帮手慕小脸 2020-05-08 19:00:15

同学你好,之前讲的方式例如:from表单这种。

这里的form表单,请求参数需要设置为post,并且要设置entype属性为文件上传的标识,如下所示:

http://img1.sycdn.imooc.com//climg/5eb534ab09821fcc07950199.jpg

具体内容同学可以参考《步骤二:从网页搭建入门JavaWeb》三步骤:登录注册

http://img1.sycdn.imooc.com//climg/5eb5363909d469b807300375.jpg

链接如下:

https://class.imooc.com/course/899

祝学习愉快~


  • 提问者 慕沐8221787 #1
    基于springmvc或者springboot框架,如果上传的不只是文件,还有多个其他参数,其他参数可以封装到一个类中,在controller的方法中能用类的对象作为形参来接收吗?这种情况是不是也不可以用springmvc的表单?
    2020-05-09 14:53:21
  • 好帮手慕小班 回复 提问者 慕沐8221787 #2
    同学你好,1、首先在controller的方法中是可以将类的对象作为形参来接收的,但是这个对象中不包括文件内容。 2、如果使用springmvc的表单来完成文件的提交,因为案例项目中并没有涉及这些内容,老师可能需要更多的时间来测试验证这个功能,需要一点时间,同学可以需要等待一段时间。我们会尽快测试回复的。 继续加油 祝:学习愉快~
    2020-05-09 19:58:54
  • 提问者 慕沐8221787 #3
    好的,对基于springmvc或者springboot框架,需要从前端上传多个参数及文件,常用的接收方法是什么样的,请老师给出一个通行的处理方式,谢谢!
    2020-05-09 21:35:59
好帮手慕小脸 2020-05-08 16:00:23

同学你好,文件上传需要对文件进行处理,不能使用modelAttribute这种方式上传,如果要上传文件,可以使用之前讲的方式上传文件

祝学习愉快~

  • 提问者 慕沐8221787 #1
    之前讲的什么方式,能具体讲一下吗?
    2020-05-08 16:16:50
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
SSM主流框架入门与综合项目实战2018版
  • 参与学习           人
  • 提交作业       205    份
  • 解答问题       4317    个

Java中非常实用的SSM整合开发内容,从Spring开始,到MyBaits的进阶内容,再到SpringMVC的应用,最后是SSM整合开发案例,逐步深入,助你成长为一名Java工程师!

了解课程
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码