关于上传文件的问题
如果在jsp页面使用了springmvc表单,向controller上传参数(通过modelAttribute),同时还要上传文件,该如何处理呢?比如课程中报销单创建时需要提交差旅票据扫描件上传,类似这样的应用场景
54
收起
正在回答
4回答
同学你好,pom文件中的依赖有如下:
<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>
祝:学习愉快~
好帮手慕阿满
2020-05-10 14:36:26
同学你好,如下给出一种SpringMVC使用form表单上传文件:
实体类Goods:
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:
<?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:
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页面:
<%@ 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配置:
<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>
项目结构:

添加商品后,target目录下的upload会出现上传的文件。
祝:学习愉快~
好帮手慕小脸
2020-05-08 19:00:15
同学你好,之前讲的方式例如:from表单这种。
这里的form表单,请求参数需要设置为post,并且要设置entype属性为文件上传的标识,如下所示:

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

链接如下:
https://class.imooc.com/course/899
祝学习愉快~
SSM主流框架入门与综合项目实战2018版
- 参与学习 人
- 提交作业 205 份
- 解答问题 4317 个
Java中非常实用的SSM整合开发内容,从Spring开始,到MyBaits的进阶内容,再到SpringMVC的应用,最后是SSM整合开发案例,逐步深入,助你成长为一名Java工程师!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星