前端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 action="${pageContext.request.contextPath }/sy/clz_upload.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="cid" value="${result.cid }"><br>
<input type="hidden" name="cname" value="${result.cname }"><br>
<input type="hidden" name="cteacher" value="${result.cteacher }"><br>
图片:<input type="file" name="img"><br>
<input type="submit">
</form>
</body>
</html>
编写子控制器并封装参数:
/**
* 按照指定的格式去接受参数变量
* 1.上传的文件
* 2.上传的文件名
* 3.上传的文件类别
*/
private File img;
private String imgFileName;
private String imgContentType;
public File getImg() {
return img;
}
public void setImg(File img) {
this.img = img;
}
public String getImgFileName() {
return imgFileName;
}
public void setImgFileName(String imgFileName) {
this.imgFileName = imgFileName;
}
public String getImgContentType() {
return imgContentType;
}
public void setImgContentType(String imgContentType) {
this.imgContentType = imgContentType;
}
/**
* 跳转到文件上传界面
*/
public String preUpload() throws Exception {
this.result = this.clzDao.list(clz, null).get(0);
this.req.setAttribute("result", result);
return "upload";
}
/**
* 上传图片的方法
*/
public String upload() throws Exception {
// img代表客户选择的文件或图片,接下来要将图片上传到其他地方
String destDir="F:/ruanjian/upload/";
String serverDir="/uploadImages";
// 源文件考到目的地
FileUtils.copyFile(img, new File(destDir+"/"+imgFileName));
//将图片加到数据库
//数据库保存的值是:/uploadImages/xx.png
//图片是在:F:/ruanjian/upload/
//访问:http://localhost:8080/struts/uploadImages/xx.png
clz.setPic(serverDir+"/"+imgFileName);
this.clzDao.edit(clz);
return TOLIST;
}
selver.xml中做路径配置:
<result name="upload">/upload.jsp</result>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="sy" extends="base" namespace="/sy">
<action name="/clz_*" class="com.mwy.web.ClzAction" method="{1}">
<result name="list">/clzList.jsp</result>
<result name="toEdit">/clzEdit.jsp</result>
<!-- 以前的写法:/book.action?methodName=list
type属性有四个选项:
1、默认forward:标签体对应的转发页面;
2、action:标签体对应的转发的Action后台方法;
3、redirect:标签体对应的重定向方法:
4、redirectAction:标签体对应的重定向;
-->
<result name="toList" type="redirectAction">/clz_list</result>
<result name="upload">/upload.jsp</result>
</action>
</package>
</struts>
修改 :<td>${j.pic }</td>
改为 :<td><img alt="" src="${j.pic }" style="width: 50px;height: 70px"></td>
增加 (加在操作中) :<a href="${pageContext.request.contextPath }/sy/clz_preUpload.action?cid=${j.cid}">图片上传</a>
server.xml中增加:
<Context path="/uploadImages" docBase="E:/dzl/QQ/image"/>
运行结果: