struts2上传图片的全过程

多个上传文件

1、写一个上传的jsp页面upload_image.jsp,内容如下:

<body>
<center>
       <font color="red"><s:fielderror/></font>
              <s:form action="uploadOne" method="post" enctype="multipart/form-data">
                     <s:file name="file" label="文件1"></s:file>
                     <s:file name="file" label="文件2"></s:file>
                     <s:file name="file" label="文件3"></s:file>
                     <s:file name="file" label="文件4"></s:file>
                     <s:submit label="上传"/>
              </s:form>      
</center>
</body>

解析:A、 form里面的method必须是post,enctype="multipart/form-data"上传文件必须这样写
           B、<s:fielderror/>这个是图片格式或者大小出错的错误提示---要在struts.xml里面先配置
           C、name="file",批量上传name的值要一样


2、创建一个action--我的包是com.upload.one
public class UploadImageAction extends ActionSupport{
       private List<File> file;
       private List<String> fileFileName;
       private List<String> fileContentType;
      
       public String execute() throws IOException{
       //得到工程保存图片的路径
               String root = ServletActionContext.getRequest().getRealPath("/upl oad");
               //循环上传的文件
               for(int i = 0 ; i < file.size() ; i ++){
                       InputStream is = new FileInputStream(file.get(i));
                        //得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
                       File destFile = new File(root,this.getFileFileName().get(i));
                       //把图片写入到上面设置的路径里
                       OutputStream os = new FileOutputStream(destFile) ;
                       byte[] buffer = new byte[400 ];
                       int length   = 0 ;
                       while((length = is.read(buffer))>0){
                               os.write(buffer, 0, length);
                       }
                       is.close();
                       os.close();
               }
               return SUCCESS;
       }
}

解析:在这个action里面做了几个测试
         要在WebRoot下面新建一个文件夹--upload
          在命名的时候要遵循一个规律,这个样的话fileFileName自动的把图片名称 一个一个的添加到里面,不用自己添加

3、配置struts.xml文件
<struts>
       <!-- 指定国际化资源文件的baseName为messageResource -->
        <constant name="struts.custom.i18n.resources" value="messageResource"/>
      
       <!-- 设置该应用使用的解码集 -->
         <constant name="struts.i18n.encoding" value="utf-8"/>
 
         <!-- 上传的全部图片的最大限制-->
         <constant name="struts.multipart.maxSize" value="1024102400"/>
        
       <!-- 配置action->
       <package name="default" extends="struts-default">
              <action name="uploadOne" class="com.upload.one.UploadImageAction" >
             
                     <!-- 限制图片的格式和图片的大小 -->
                     <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" />
                    
                     <result name="success">/showImage.jsp</result>
                     <result name="input">/upload_image.jsp</result>
              </action>
       </package>

       <constant name="struts.multipart.saveDir" value="d:/test"></constant>
</struts>

解析:
       A、因为在这里我限制了图片的格式和大小,如果不配置国际化资源文件,那么在页面引入<s:fielderror/>
            的时候,显示出的内容不友好,于是自己定义出错显示的内容

       B、在action配置里面,限制了单张图片的大小<param name="maximumSize">102400</param>
            如果不再package外面(<constant name="struts.multipart.maxSize" value="1024102400"/>)限制总的上传大小
                     那么,当你上传的单个图片超过限定的大小,没事反应,但是后台会报错

       C、<constant name="struts.multipart.saveDir" value="d:/test"></constant>临时存放文件的路径
            如果不要这个路径,就会在控制台打印Unable to find 'struts.multipart.saveDir' property setting. Defaulting to             javax.servlet.context.tempdir

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);    
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值