文件上传有三种方式
1.上传到tomcat服务器。
一般不推荐使用。
原因:
存在两点瑕疵:
①上传后需要刷新一遍,图片才会出来。
②重启tomcat后,图片会丢失。
2.上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系(主要使用的方式)
上传文件的跳转页面:
<%@ 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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/sy/MyClass_upload.action" method="post" enctype="multipart/form-data">
<input type="hidden" value="${result.cid }" name="cid"><br>
<input type="hidden" value="${result.cname }" name="cname"><br>
<input type="hidden" value="${ result.cteacher}" name="cteacher"><br>
<!--
上传文件
-->
<input type="file" name="file"><br>
<input type="submit" value="ok">
</form>
</body>
</html>
子控制器添加几个属性值:
private File file;
private String fileFileName;
private String fileContentType;
跳转页面的方法:
/**
* 图片上传跳转页面
* @return
*/
public String preUpload() {
try {
if(myClass.getCid()!=0) {
this.result=classDao.findByCnameallClassListAndPage(myClass, null).get(0);
}
} catch (InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "preUpload";
}
添加server.xml的配置
<Context docBase="D:/T237_tu/" path="/struts/upload"></Context>
/**
* 从本地读取文件到服务器
* @param source
* @param target
* @throws Exception
*/
public void copyFile(File source,File target) throws Exception {
BufferedInputStream in=new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(target));
byte[] bbyte=new byte[1024];
int len=0;
while((len=in.read(bbyte))!=-1) {
out.write(bbyte, 0, len);
}
in.close();
out.close();
}
图片上传
/**
* 图片上传
* @return
* @throws IOException
*/
public String upload() {
//图片上传的真实目录
String realDri="D:/T237_tu";
//服务器中存放图片的目录
String serverDri="/upload";
try {
//FileUtils.copyFile(file, new File(realDri+"/"+fileFileName));
//将本地图片上传到服务器中某一真实目录下(从本地读取文件到服务器中)
copyFile(file, new File(realDri+"/"+fileFileName));
myClass.setCip(serverDri+"/"+fileFileName);
classDao.editMyClassByCid(myClass);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
添加struts-sy.xml的配置
<result name="preUpload">/preUpload.jsp</result>
主页面的上传文件按钮:
<a href="${pageContext.request.contextPath}/sy/MyClass_preUpload.action?cid=${c.cid }">上传</a>
主页面的图片展示
<input style="width: 100px;height: 100px" type="image" src="${pageContext.request.contextPath}${c.cip }">
效果:
3.在数据库表中建立二进制字段,将图片存储到数据库 。
现在这种方式已经淘汰
原因:
占用空间大
查询耗时长