Jslfl【软件开发技术笔记】

Struts2文件上传记要

先写我的实践过程:

Struts.xml

<!– 上传临时文件目录 –>

    <constant name=”struts.multipart.saveDir” value=”D:/jqGis_tmp” />

    <!– 上传文件大小 限制  5M–>

    <constant name=”struts.multipart.maxSize” value=”5242880″/>

<!– 文件上传下载测试 –>

              <action name=”upload” method=”upload”>

                     <interceptor-ref name =”fileUploadStack” >

                            <!– 上传文件类型限制 –>

                <param name =”fileUpload.allowedTypes” >

                    image/bmp,image/png,image/gif,image/jpeg,image/jpg

                </param >

                <!– 上传文件大小限制 (字节)1M–>

                <param name=”fileUpload.maximumSize”>1048576</param>

            </interceptor-ref >

                     <result name=”input” >

                            /WEB-INF/jsp/file.jsp

                     </result>

                     <result name=”success” >

                            /WEB-INF/jsp/file.jsp

                     </result>

              </action>

              <action name=”download” method=”download”>

                     <result type=”stream”>

                <param name=”contentType”>application/octet-stream</param><!– 下载文件的文件类型 :不限制 –>

                <param name=”inputName”>downloadStream</param><!– action中的 getDownloadStream方法  –>

                <param name=”contentDisposition”>attachment;filename=”${downloadName}”</param><!– 文件名一般经过编码  –>

                <param name=”bufferSize”>4096</param><!– 缓冲区大小  –>

            </result>

              </action>

Action:

private File[] upfiles;//上传文件集,struts临时文件

    private String[] upfilesFileName;//上传文件的真实文件名

    private String[] upfilesContentType;//上传文件的类型

    private List<Map<String,String>> fileList;//测试下载用

    private String downloadPath;//下载文件的路径

    private String downloadName;//下载文件名称

    private InputStream downloadStream;//提供下载文件的数据流

/**

     * 文件上传

     * @return

     */

    public String upload(){

       fileList = new ArrayList<Map<String,String>>();//传到页面提供下载测试

       if(upfiles != null){

           //保存文件

           for(int i = 0 ;i<upfiles.length ; i++){

              File tmpfFile = upfiles[i];

              String newFilePath = servletContext .getRealPath(Global.FILE_SPACE + “upload/app/photo/”

                     + FileUtils.creatNewNameByTime(FileUtils.getFileSuffix(upfilesFileName[i])));

              FileUtils.copyFile(tmpfFile.getPath(), newFilePath);

              logger.info(“====上传文件 ” + upfilesFileName[i] + ” 成功!” + newFilePath);

              //提供下载的 测试

              Map<String,String> file = new HashMap<String,String>();

              file.put(“fileName”, upfilesFileName[i]);

              file.put(“downloadPath”, “upload/app/photo/”

                     + FileUtils.creatNewNameByTime(FileUtils.getFileSuffix(upfilesFileName[i])));

              fileList.add(file);

           }

       }

       return SUCCESS;

    }

    /**

     * 文件下载

     * @return

     * @throws UnsupportedEncodingException

     */

    public String download() throws UnsupportedEncodingException{

       String filePath = Global.FILE_SPACE + downloadPath;

       downloadName = new String(downloadName.getBytes(), “ISO8859-1”);//下载文件名编码

       this.downloadStream = servletContext.getResourceAsStream(“/” + filePath);

       return SUCCESS;

    }

public class FileUtils {

    private static Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**

     * 得到文件名中的扩展名

     * @param fileName

     * @return

     */

    public static String getFileSuffix(String fileName){

         return fileName.substring(fileName.lastIndexOf(“.”));

    }

    /**

     * 根据时间创建一个文件名,如:20120304122321.jpg

     * @param suffix 文件扩展名,如:“.jpg

     * @return

     */

    public static String creatNewNameByTime(String suffix){

       return DateUtil.format(new Date(), “yyyyMMddHHmmssSSS”) + suffix;

    }

    /**

     * 复制单个文件,如果目标文件存在,则不覆盖

     * @param srcFileName 待复制的文件名

     * @param descFileName 目标文件名

     * @return 如果复制成功,则返回true,否则返回false

     */

    public static boolean copyFile(String srcFileName, String descFileName) {

       return FileUtils.copyFileCover(srcFileName, descFileName, false);

    }

    /**

     * 复制单个文件

     * @param srcFileName 待复制的文件名

     * @param descFileName 目标文件名

     * @param coverlay 如果目标文件已存在,是否覆盖

     * @return 如果复制成功,则返回true,否则返回false

     */

    public static boolean copyFileCover(String srcFileName,

           String descFileName, boolean coverlay) {

       File srcFile = new File(srcFileName);

       // 判断源文件是否存在

       if (!srcFile.exists()) {

           log.debug(“复制文件失败,源文件” + srcFileName + “不存在!”);

           return false;

       }

       // 判断源文件是否是合法的文件

       else if (!srcFile.isFile()) {

           log.debug(“复制文件失败,” + srcFileName + “不是一个文件!”);

           return false;

       }

       File descFile = new File(descFileName);

       // 判断目标文件是否存在

       if (descFile.exists()) {

           // 如果目标文件存在,并且允许覆盖

           if (coverlay) {

              log.debug(“目标文件已存在,准备删除!”);

              if (!FileUtils.delFile(descFileName)) {

                  log.debug(“删除目标文件” + descFileName + “失败!”);

                  return false;

              }

           } else {

              log.debug(“复制文件失败,目标文件” + descFileName + “已存在!”);

              return false;

           }

       } else {

           if (!descFile.getParentFile().exists()) {

              // 如果目标文件所在的目录不存在,则创建目录

              log.debug(“目标文件所在的目录不存在,创建目录!”);

              // 创建目标文件所在的目录

              if (!descFile.getParentFile().mkdirs()) {

                  log.debug(“创建目标文件所在的目录失败!”);

                  return false;

              }

           }

       }

       // 准备复制文件

       // 读取的位数

       int readByte = 0;

        InputStream ins = null;

       OutputStream outs = null;

       try {

           // 打开源文件

           ins = new FileInputStream(srcFile);

           // 打开目标文件的输出流

           outs = new FileOutputStream(descFile);

           byte[] buf = new byte[1024];

           // 一次读取1024个字节,当readByte-1时表示文件已经读取完毕

           while ((readByte = ins.read(buf)) != -1) {

              // 将读取的字节流写入到输出流

              outs.write(buf, 0, readByte);

           }

           log.debug(“复制单个文件” + srcFileName + “到” + descFileName

                  + “成功!”);

           return true;

       } catch (Exception e) {

           log.debug(“复制文件失败:” + e.getMessage());

           return false;

       } finally {

           // 关闭输入输出流,首先关闭输出流,然后再关闭输入流

           if (outs != null) {

              try {

                  outs.close();

              } catch (IOException oute) {

                  oute.printStackTrace();

              }

           }

           if (ins != null) {

              try {

                  ins.close();

              } catch (IOException ine) {

                  ine.printStackTrace();

              }

           }

       }

    }}

Jsp:

<form action=${ctx }/sysset/upload.do method=”post” enctype=”multipart/form-data”>

<input type=”file” name=”upfiles” />

<input type=”file” name=”upfiles” />

<input type=”file” name=”upfiles” />

<input type=”submit” value=”上传”/>

<s:fielderror />

</form>

<table>

<c:forEach items=${fileList } var=“f”>

<tr>

    <td><a href=${ctx }/sysset/download.do?downloadPath=${f.downloadPath }&downloadName=${f.fileName }>${f.fileName }</a> </td>

    </tr>

</c:forEach>

</table>

详细参考:http://www.jslfl.cn/?p=59

Comments are currently closed.