基于struts2框架文件的上传与下载

在开发一些社交网站时,需要有允许用户上传自己本地文件的功能,则需要文件的上传下载代码。

首先考虑的是文件的储存位置,这里不考虑存在数据库,因为通过数据库查询获取十分消耗资源与时间,故需将数据存储在服务器上。

1. 前台页面的代码:

<form action="photo-up" method="post" enctype="multipart/form-data">            
            上传图片: <input type="file" name="myFile">
            <!--或者<s:file name="myFile" label="FILE"/> -->

            <input type="submit" value="上传"/><s:fielderror id="error"/>
        </form>
<s:file name="myFile" label="FILE"/>

上面的重要属性是name,要求如后台的文件定义名一样。

2. 文件上传后台代码(struts2的Action控制类):

public class PhotoAction extends ActionSupport {

    private static final long serialVersionUID = 6897968438458946989L;
   private File myFile;
    private String myFileContentType;
    private String myFileFileName;
    //定义以上三个变量,myFile是接受前台的文件,要求名字与name属性一样,其他的见名知意(就当固定格式)
    User user = (User)ActionContext.getContext().getSession().get("user") ;
    
    public String up() throws Exception {
        //创建输入流
        InputStream is = new FileInputStream(myFile) ;
        //设置不同用户的文件保存目录
        String photoPath = ServletActionContext.getServletContext()
                        .getRealPath("/user/photo/" + user.getUserName()) ;
        File filePhotoPath = new File(photoPath);
        if(!filePhotoPath.isDirectory()) {
            filePhotoPath.mkdir();
        }
        //解决中文文件名问题,采用UUID获取随机字符串
        String extension = FilenameUtils.getExtension(getMyFileFileName());//获取文件的拓展名
        String filename = UUID.randomUUID().toString() + "."+ extension;
        File toFile = new File(filePhotoPath, filename) ;
        //输出流
        OutputStream os = new FileOutputStream(toFile) ;
        byte[] buf = new byte[1024] ;
        int lenth ;
        while((lenth = is.read(buf)) >0 ){
            os.write(buf, 0, lenth);            
        }
        is.close();
        os.close();
        return "up";
    }
//属性的get、set方法
  public File getMyFile() {
        return myFile;
    }
    public void setMyFile(File myFile) {
        this.myFile = myFile;
    }
    public String getMyFileFileName() {
        return myFileFileName;
    }
    public void setMyFileFileName(String myFileFileName) {
        this.myFileFileName = myFileFileName;
    }
    public String getMyFileContentType() {
        return myFileContentType;
    }
    public void setMyFileContentType(String myFileContentType) {
        this.myFileContentType = myFileContentType;
    }
    
}

此代码将文件存储在  (Web应用程序的根目录的绝对路径)/user/photo/(userName) 下面。

在struts.xml文件中配置文件限制要求:

<action name="photo-*" class="photoAction" method="{1}">

            <!-- 配置fileUpload拦截器 -->
            <interceptor-ref name="fileUpload">
                <!-- 配置允许上传文件类型 -->
                <param name="allowedTypes">image/bmp,image/pjpeg,image/gif,image/png</param>
                <!-- 配置允许上传文件大小最大值 -->
                <param name="maximumSize">512000</param>
            </interceptor-ref>
<result name="up" type="redirectAction">photo-showPhoto</result> <result name="input" type="redirectAction">photo-showPhoto</result> <result name="showPhoto">/showphoto.jsp</result> </action>

3. 文件的下载代码

  文件的下载代码比较简单,只需要得到web应用程序目录下文件的所在位置即可,然后放在一个超链接里面点击就可以浏览或下载。

public String showPhoto(){
        String photoPath = ServletActionContext.getServletContext()
                .getRealPath("/user/photo/" + user.getUserName()) ;
        File file = new File(photoPath) ;
    //获取该目录下所有的文件名
        String[] photoList = file.list() ;
    //将获取文件名的集合放在request里       
     ServletActionContext.getRequest().setAttribute("photoList", photoList);
        return "showPhoto" ;
    }

4. 返回页面,显示文件连接:

<table align="center" border="1" cellpadding="0" cellspacing="10">
        <tr>
            <s:iterator value="#request.photoList" var="photo" status="stu">
                <td>
                    <a href='user/photo/${sessionScope.user.userName }/<s:property value="photo"/>'>
                    <img alt="" src='user/photo/${sessionScope.user.userName }/<s:property value="photo"/>'
                     width="100" height="120"></a>
                </td>
                    <s:if test="(#stu.index + 1) % 6 == 0">
                        </tr>
                        <tr>
                    </s:if>
            </s:iterator>    
        </tr>
</table>    

以上有个在table里自动换行的小技巧,当(集合下标+1)能整除6就加</tr>结束一行,加<tr>开始新的一行。

原文地址:https://www.cnblogs.com/hfblogs/p/5439653.html