首页 > 代码库 > Struts文件上传

Struts文件上传

技术分享

如果文件上传不成功,默认是return "input"
<result name="success">/success.jsp</result>
    <result name="input">/index.jsp</result>




单个文件上传
ServletContext context=ServletActionContext.getServletContext();就是获取webroot
        String dir=context.getRealPath("/files/"+pptFileName);
        System.out.println(dir);
        
        FileOutputStream fos=new FileOutputStream(dir);
        FileInputStream fis=new FileInputStream(ppt);
        
        byte[] buffer=new byte[1024];
        int len=0;
        while ((len=fis.read(buffer))!=-1) {
            fos.write(buffer, 0, len);
        }
        
        fos.close();
        fis.close();
上传限制
<interceptors>
    <interceptor-stack name="fileUp">
    <interceptor-ref name="defaultStack">
    <param name="fileUpload.maximumSize">2000</param>
    <param name="fileUpload.allowedTypes">text/plain,text/plain</param>
    <param name="fileUpload.allowedExtensions">html,dtd,xml</param>
    </interceptor-ref>
    </interceptor-stack>
    </interceptors>
    
    image/png,image/bmp,image/jpg  
    
    
    
    
    <default-interceptor-ref name="fileUp"></default-interceptor-ref>
<s:form action="s/upload_upload" method="post"
            enctype="multipart/form-data" theme="simple">
        <s:fielderror name="ppt"></s:fielderror>
            file:<s:file name="ppt" label="file"></s:file>    
            pptDescA:<s:textfield name="pptDesc[0]" label="pptDescA"></s:textfield>


while (iterator.hasNext()) {
                File file = (File) iterator.next();
                String dir=context.getRealPath("/resource/image/knowledge/upLoad/"+caseImgFileName.get(caseImg.));
                System.out.println(dir+"***********dir");
                try {
                    fis=new FileInputStream(file);
                    fos=new FileOutputStream(dir);
                    
                    byte[] bs=new byte[1024];
                    int len=0;
                    while((len=fis.read(bs))!=-1){
                        fos.write(bs, 0, len);
                    }
                    
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    System.out.println("文件输入错误");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    try {
                        fos.close();
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.out.println("输入流、输出流关闭错误");
                    }
                    
                }
            }
String rpath="resource/image/knowledge/upLoad/";
存储在数据库中的路径不能是绝对路径一定要是相对路径

 

Struts文件上传