多个上传文件
1、写一个上传的jsp页面upload_image.jsp,内容如下:
<body><center>
</center>
</body>
解析:A、 form里面的method必须是post,enctype="multipart/form-data"上传文件必须这样写
2、创建一个action--我的包是com.upload.one
public class UploadImageAction extends ActionSupport{
}
解析:在这个action里面做了几个测试
3、配置struts.xml文件
<struts>
</struts>
解析:
4、messageResource_zh_CN.properties 配置文件的内容
#上传文件类型不允许的提示信息
struts.messages.error.content.type.not.allowed=\u4E0A\u4F20\u7C7B\u578B\u9519\u8BEF
#上传文件太大的提示信息
struts.messages.error.file.too.large=\u4E0A\u4F20\u6587\u4EF6\u592A\u5927
解析:当图片的格式不对,上传大小不对时,就会在页面显示相应的错误信息
单个文件上传
upload.java
public class Upload {
public String upload(File image,String savePath,String imageFileName)
{
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream(savePath + "\\" +imageFileName); // 建立文件输出流
fis = new FileInputStream(image); // 建立文件上传流
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0)
{
fos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(fos, fis);
}
return "D:\\apache-tomcat-6.0.39\\webapps\\Test\\UploadFile\\"+imageFileName;
}
private void close(FileOutputStream fos, FileInputStream fis) {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println("FileInputStream关闭失败");
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
System.out.println("FileOutputStream关闭失败");
e.printStackTrace();
}
}
}
}
upload.jsp
<foform action="${pageContext.request.contextPath}/upload/Clients!addg" name="from1" enctype="multipart/form-data" method="post">
<table bordercolor="blue" border="1px solid blue" align="center">
<tr><td>认证图片:</td><td><input type="file" name="image"> </td> </tr>
<tr><td><input type="submit" value="添加"></td>
</table>
</form>
struts.xml配置
<package name="upload" extends="struts-default">
<action name="Clients" class="Client">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/bmp,image/png,image/gif,image/jpeg,image/jpg
</param>
<param name="maximumSize">102400</param>
</interceptor-ref>
<!-- 默认的拦截器,必须要写 -->
<interceptor-ref name="defaultStack" />
<param name="savePath">/UploadFile</param>
</action>
</package>
action文件
private File image; // 封装上传文件域的属性
private String imageContentType; // 封装上传文件类型的属性
private String imageFileName; // 封装上传文件名的属性
private String savePath;// 接受依赖注入的属性
getter和setter方法,只有这个需要改
public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}