文件上传-->upload.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload_file.jsp' starting page</title>
</head>
<body>
<s:form action="/multi-upload-2" method="post"
enctype="multipart/form-data">
<s:file name="upload" label="upload1" />
<s:file name="upload" label="upload2" />
<s:file name="upload" label="upload3" />
<s:submit />
</s:form>
</body>
</html>
MultiUploadFileAction:
//注意这里的第一个属性名字不是必须这样,但是set方法却必须是下列属性对应的参数
//(upload前缀取决于form表单中的s:file name="")
private File[] upload; (private List<File> upload)
private String[] uploadContentType; (private List<String> uploadContentType)
private String[] uploadFileName; (private List<String> uploadFileName)
文件上传的步骤:
1. 创建上传目录:
String path = ServletActionContext.getServletContext.getRealPath("自定义路径");
File uploadPath = new File(path);
if(!uploadPath.exists())
uploadPath.mkdirs();
FileInputStream in = null;
FileOutputStream out = null;
2.生成uuidFileName
String extendedName = uploadFileName[i].subString(uploadFileName[i].lastIndexOf("."));
String uuidFileName = UUID.randomUUID().toString() + extendedName;
3.创建文件输入、输出对象
in = new FileInputStream(upload[i]);
out = new FileOutputStream(uploadPath + "/" + uuidFileName);
4.字节流读写数据
byte[] buf = new byte[1024];
int len = -1;
while((len = in.read(buf)) != -1){
out.write(buf, 0, len);
}
5.关闭流对象
out.close();
in.close();