下面是部分代码
jsp页面用一个form表单提交
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" class="form-control" name="upload">
<button type="submit" >提交</button>
</form>
action.java
private File upload;
private String uploadContentType;
private String uploadFileName;
……
public void upload() throws IOException{
String path = ServletActionContext.getServletContext().getRealPath("/photo");
//在服务器路径下判断是否有photo这个文件夹,没有就创建一个
//但是这个文件夹是临时的,如果项目重新部署的话会被删除
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
//为了避免文件名重复,这里选择用uuid重命名(肯定不会重复)
uploadFileName = UUID.randomUUID().toString()+uploadFileName;
//将文件拷贝到服务器路径下
FileUtils.copyFile(upload, new File(file,uploadFileName));
}
……
struts.xml
//设置拦截器,拦截图片上传的类型和大小
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/bmp,image/x-png,image/gif,image/jpeg,image/jpg</param>
<param name="maximumSize">2M</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
如果想设置结果报错的话可以在app_zh_CN.properties文件下设置
struts.messages.error.to.large 文件太大
struts.message.error.content.type.not.allowed 文件类型错误
上传成功后你可以在下面这个路径下看到你创建的文件夹
其中javaeeworkspace是工作空间,PurchasePlatform是你的项目名称