---
title: "liferay5.2.3  附件上传"
author: "nilm61"
date: "2013-03-19T11:27:22Z"
tags: []
categories: ["开源软件"]
slug: "liferay5-2-3"
draft: false
lastmod: "2013-03-19T11:29:08Z"
id: 1831691
url: "https://nilm61.iteye.com/blog/1831691"
---

附件上传

 

首选说一下文件的存放位置，存放目录大致如下：

 {bundles.home}/data/document\_library/10115/0/customerDirName/0/fileName/1.0

 

 

这里主要是利用liferay现有的文档库，当然这些文件在文档库是看不到的！

 

 

下面说一下具体的实现：

 

1、**首先要在liferay项目中的service.xml  中找到需要关联附件的表对应的**entity标签,，在&lt;/entity&gt;之前加上

 

&lt;reference package-path=*"com.liferay.documentlibrary"* entity=*"DL"* /&gt;

 

大致表示的的是与文档库对应的接口相关联，只有这样才能在自己的实体类对应的service层的实现类中调用文档库提供的dlService对象，下面会看到的具体的使用的

 

例如：

 

    &lt;entity name=*"Contract"* local-service=*"true"* remote-service=*"false"*&gt;

        &lt;column name=*"contractId"* type=*"long"* primary=*"true"* /&gt;

        &lt;column name=*"companyId"* type=*"long"* /&gt;

        &lt;column name=*"name"* type=*"String"* /&gt;

 

        &lt;column name=*"haveAuthorizationBook"* type=*"boolean"* /&gt;&lt;!-- 这里是用来标示是不是有附件的一个字段--&gt;

        &lt;column name=*"authorizationBookName"* type=*"String"* /&gt;

                 &lt;!-- 这里是有附件文件的名字的字段--&gt;

 

        &lt;finder name=*"CompanyId"* return-type=*"Collection"*&gt;

            &lt;finder-column name=*"companyId"* /&gt;

        &lt;/finder&gt;

       

        &lt;!-- References --&gt;

      &lt;reference package-path=*"com.liferay.documentlibrary"* entity=*"DL"*&gt;&lt;/reference&gt;

    &lt;/entity&gt;

 

2、**就是对jsp（或者html）中的表单加上一个属性enctype=*"multipart/form-*data"**

（就是上传文件所需要的表单属性，你懂的）

 

&lt;form  action=*""*  method=*"post"*  enctype=*"multipart/form-data"*&gt;

 

这里有需要上传文件的选择框

 

&lt;inputname=*"AuthorizationBook"* size=*"70"*  type=*"file"* /&gt;

 

&lt;/form&gt;

 

**3.就是保存表单提交给服务器的处理了**

首先就是要获得一个uploadRequest 对象

 

UploadPortletRequest uploadRequest = PortalUtil.*getUploadPortletRequest*(actionRequest);

 

之后传递过来的参数都需要通过uploadRequest 对象才能够获得哦！

 

如：String name = ParamUtil.*getString*(**uploadRequest**, "name");

 

下面就是获得要上传的文件了

 

File file = uploadRequest.getFile(fileParamName);

        String fileName = uploadRequest.getFileName(fileParamName);

**byte**\[] bytes = FileUtil.*getBytes*(file);

 

 

    String dirName = TextUtil.*getAnnexPath*("contract\_authorization\_book", contract.getCreateUserId(), contract.getContractId());// 这个是用来获得附加要存放的在文档库中的路径的，可以自行定义，这里获得结果是使用字符串拼成的路径，规则是：三个参数相连接。这只是个例子，可以自由发挥的！！

 

 

 

contract.setAuthorizationBookName(fileName);

merge = contract.getHaveAuthorizationBook();

contract.setHaveAuthorizationBook(**true**);

 

ContractLocalServiceUtil.*updateContractRealtionFile*(contract, dirName, fileName,bytes, merge); //这个方法是在ContractLocalServiceImpl中实现的

 

**4.ContractLocalServiceImpl中的实现**

 

 

**publicvoid** updateContractRealtionFile(Contract contract,String dirName,String fileName,**byte**\[] bytes,**boolean** hadDirectory) **throws** SystemException, PortalException{

           

**long** companyId=contract.getCompanyId();

//下面三个是liferay中的几个常量。

String portletId = CompanyConstants.*SYSTEM\_STRING*;

**long** groupId = GroupConstants.*DEFAULT\_PARENT\_GROUP\_ID*;

**long** repositoryId = CompanyConstants.*SYSTEM*;

           

           

**if**(hadDirectory){

**try** {

    dlService.deleteDirectory(companyId, portletId, repositoryId, dirName);

        }**catch** (NoSuchDirectoryException nsde) {

    **if** (*\_log*.isDebugEnabled()) {

        *\_log*.debug(nsde.getMessage());

        }

}

}

           

dlService.addDirectory(companyId, repositoryId, dirName);

               

**try** {

    dlService.addFile(companyId, portletId, groupId, repositoryId,**dirName + File.*separator* + fileName**, 0, StringPool.*BLANK*,

contract.getCreateDate(), **new** String\[0], **new** String\[0],bytes);

}**catch** (DuplicateFileException dfe) {

    **if** (*\_log*.isDebugEnabled()) {

        *\_log*.debug(dfe.getMessage());

    }

}

contractPersistence.update(contract);

}

 

 

 

在这个方法中含有相应的逻辑处理，除了上面标红的部分要注意外，对于dlService方法的调用可以自由发挥的

 

 

**5.附件的显示**

 

&lt;c:if test=*"*&lt;%=contract.getHaveAuthorizationBook() %&gt;*"*&gt;

    &lt;li class=*"shortItem"*&gt;

    &lt;span&gt;

    &lt;liferay-ui:message key=*"authorization.book.file"* /&gt;

    &lt;/span&gt;

 

    &lt;label&gt;

&lt;a href=*"*&lt;portlet:actionURL windowState="&lt;%= LiferayWindowState.EXCLUSIVE.toString() %&gt;"&gt;

&lt;portlet:param name="&lt;%=ActionRequest.ACTION\_NAME  %&gt;" value=*"get.contract.annex.file"* /&gt;

 

&lt;portlet:param name=*"contractId"* value="&lt;%= String.valueOf(contract.getContractId()) %&gt;" /&gt;

 

&lt;portlet:param name=*"flagDirectory"* value="&lt;%=Constants.CONTRACT\_ANNEX\_AUTHORIZATION\_BOOK %&gt;" /&gt;

                    &lt;/portlet:actionURL&gt;*"*&gt;

 

&lt;%=contract.getAuthorizationBookName() %&gt;

&lt;/a&gt;&lt;/label&gt;

    &lt;/li&gt;

&lt;/c:if&gt;

 

 

6、下载

 5中已经把下载的连接写出来了，这里就是后台的处理了，如下：

String  fileName = contract.getAuthorizationBookName();

 

String  filePath = TextUtil.*getAnnexPath*("contract\_authorization\_book

", createUserId, contractId)+separator+fileName;//这个与上面保存文件使用的是同一个方法获得路径

 

 

 

            HttpServletResponse response=PortalUtil.*getHttpServletResponse*(portletResponse);

            InputStream is = **null**;

           

            **try** {

                is = DLLocalServiceUtil.*getFileAsStream*(

                        companyId, CompanyConstants.*SYSTEM*, filePath);

                **int** contentLength = (**int**)DLServiceUtil.*getFileSize*(

                        companyId, CompanyConstants.*SYSTEM*, filePath);

                response.setHeader(

                        HttpHeaders.*CACHE\_CONTROL*, HttpHeaders.*CACHE\_CONTROL\_PUBLIC\_VALUE*);

                response.setHeader(HttpHeaders.*PRAGMA*, HttpHeaders.*PRAGMA\_PUBLIC\_VALUE*);

               

                String contentDisposition =

                   "attachment; filename=\\"" + **new** String(fileName.getBytes("UTF-8"),"ISO-8859-1") + "\\"";

                response.setContentLength(contentLength);

                response.setHeader(

                        HttpHeaders.*CONTENT\_DISPOSITION*, contentDisposition);

                *write*(response, is, contentLength);

               

            }

            **finally** {

                ServletResponseUtil.*cleanUp*(is);

            }  

 

 

 

下面是就是附带的几个下载的时候需要的方法

 

 

    **publicstaticvoid** write(

            HttpServletResponse response, InputStream is, **int** contentLength)

        **throws** IOException {

 

        OutputStream os = **null**;

 

        **try** {

            **if** (!response.isCommitted()) {

                **if** (contentLength &gt; 0) {

                    response.setContentLength(contentLength);

                }

 

                os = **new** BufferedOutputStream(response.getOutputStream());

 

                **int** c = is.read();

 

                **while** (c != -1) {

                    os.write(c);

 

                    c = is.read();

                }

            }

        }

        **finally** {

            *cleanUp*(os, is);

        }

    }

   

    **publicstaticvoid** cleanUp(OutputStream os, InputStream is) {

        *cleanUp*(os);

        *cleanUp*(is);

    }

    **publicstaticvoid** cleanUp(OutputStream os) {

        **try** {

            **if** (os != **null**) {

                os.flush();

            }

        }

        **catch** (Exception e) {

            **if** (*\_log*.isWarnEnabled()) {

                *\_log*.warn(e);

            }

        }

 

        **try** {

            **if** (os != **null**) {

                os.close();

            }

        }

        **catch** (Exception e) {

            **if** (*\_log*.isWarnEnabled()) {

                *\_log*.warn(e);

            }

        }

    }

    **publicstaticvoid** cleanUp(InputStream is) {

        **try** {

            **if** (is != **null**) {

                is.close();

            }

        }

        **catch** (Exception e) {

            **if** (*\_log*.isWarnEnabled()) {

                *\_log*.warn(e);

            }

        }

    }

   

 

 

 

 

附注，因为在程序涉及到了比较多的逻辑处理，这里写是最主要的过程，具体的逻辑处理可以自己发挥！