从今天起开始写java学习笔记
1. Struts中的form为:TestForm.java
其中定义
//FormFile类型
private FormFile file;
2.Struts中的aciton为:TestAction.java
//execute方法
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
TestForm testForm = (TestForm) form;
FormFile file = testForm.getFile();
//获取文件名
String filename = file.getFileName();
System.out.println(filename);
//获取绝对路径
//String path = servlet.getServletContext().getRealPath("/data") + "//";
//相对路径
String path = "D://";
System.out.println(path);
//用IO读写
try {
InputStream stream = file.getInputStream();
OutputStream bos = new FileOutputStream(path + file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[512];
while ( (bytesRead = stream.read(buffer, 0, 512)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
System.out.println("上传完成");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
3.对应页面 test.jsp
<html>
<head>
<title>JSP for TestForm form</title>
</head>
<body>
<form name="testForm" method="post" action="/file/test.do" enctype="multipart/form-data">file : <input type="file" name="file" value="">
<br />filename : <input type="text" name="filename" value="">
<br />
<input type="submit" value="Submit">
<input type="submit" name="org.apache.struts.taglib.html.CANCEL" value="Cancel" οnclick="bCancel=true;">
</form>
</body>
</html>