1.前台页面
1.1.我们可以使用s标签中的from表单,也可以直接使用from表单
<h1>上传</h1>
<s:form method="post" action="uploadAction_upload" namespace="/sy" enctype="multipart/form-data">
<s:file name="file"/>
<s:submit value="ok"/>
</s:form>
2.后台页面
2.2,需要注意的是 <s:file name=“file”/>的name是什么
File file 就是什么
String fileContentType //就是加上ContentType
String fileFileName; // 加上FileName
public class UploadAction extends BaseAction {
private File file; // 上传文件
private String fileContentType;// 上传文件的类型
private String fileFileName; // 上传文件的name
private String serverDir = "/upload"; // 定义一个盘符
/**
* 上传图片的方法
*
* @return
*/
public String upload() {
System.out.println("文件:" + file);
System.out.println("类型" + fileContentType);
System.out.println("文件名" + fileFileName);
System.out.println("=================");
String realPath = getRealPath(serverDir + "/" + fileFileName);
System.out.println(realPath);
try {
// 获取文件真实路径
FileUtils.copyFile(file, new File(realPath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
/**
* 获目录的真实路径
*
* @param string
* 指的是本地路径(相对于工程WebContent所在的路径)
* @return
*/
private String getRealPath(String path) {
return application.getRealPath(path);
}
3.我们来看看结果
E:\EclipseXM\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Struts2_01\upload\捕获3.PNG
文件:E:\EclipseXM\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Struts2_01\upload_c7a4c4bb_5341_495a_a982_1cece18a8098_00000001.tmp
类型image/jpeg
文件名QQ图片20181009163047.jpg
=================
E:\EclipseXM\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Struts2_01\upload\QQ图片20181009163047.jpg