1.文件上传三种上传方式:
1、上传到tomcat服务器 ,项目在哪里,图片就在哪里。
2、上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系文件服务器和web服务器通常是一个,但是文件目录与Tomcat目录肯定不是同一个。
3、在数据库表中建立二进制字段,将图片存储到数据库(安全性比第二种高)。
struts文件上传注意事项
1.上传页面多功能表单
enctype="multipart/form-data"
2.servlet.xml 配置映射地址(上传到指定文件才需要配置)
<Context docBase="D:/EasyUI/upload" path="/uploadImages"/>
3.struts必须按照指定的格式去接收参数变量
2.指定文件目录上传
2.1前端文件上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/sy/clz_uploads.action" method="post" enctype="multipart/form-data">
id <input name="cid" hidden="true" value="${result.cid }"/>
名字 <input name="cname" value="${result.cname}"/>
老师 <input name="cteacher" hidden="true" value="${result.cteacher}"/>
图片:<input type="file" name="img"><br>
<input type="submit">
</form>
</body>
</html>
子控制器(ClzAction)
package com.wyy.web;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.wyy.dao.ClzDao;
import com.wyy.entity.clz;
import com.zking.util.PageBean;
public class ClzAction extends BaseAction<clz>{
private clz clz=new clz();
private ClzDao cdao=new ClzDao();
/**
* img 上传的文件
* imgFileName 文件的文件名
* imgContentType 文件类别
*/
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 uploads() throws Exception {
//图片真实存放路径
String destDir="D:/EasyUI/upload";
//映射地址
String serverDir="/uploadImages";
FileUtils.copyFile(img, new File(destDir+"/"+imgFileName));
clz.setPic(serverDir+"/"+imgFileName);
this.cdao.upd(clz);
return TOLIST;
}
@Override
public clz getModel() {
return clz;
}
}
图片上传效果