Spring3.0上传和下载完整分析和源代码

首先是表单(采用springMVC模式,标签模板)documentForm.jsp

<%@ page contentType="text/html;charset=utf-8"%>
<%@ include file="/commons/taglibs.jsp"%>

<template:insert template="/commons/templates/form.jsp">
 <!-- 指定标题 -->
 <template:put name="title">项目文档信息编辑</template:put>

 <!-- 指定head标签之间的附加内容-->
 <template:put name="head">
  <script language="javascript" src="${ctx}/scripts/datetimeSelect.js"
   type="text/javascript"></script>
  <script language="javascript" type="text/javascript">
 // prepare the form when the DOM is ready
 $(document).ready(function() {
  //当表单提交时执行验证
   var validator = $("#inputForm").validate( {
    //表单提交的处理
     submitHandler : function() {
      //ajax提交表单 指定form名称和成功后跳转的地址
      AjaxForm.submit("#inputForm",
        "${ctx}/project/document/list.view");
     }
    });
   if ("${action}".indexOf("insert") >= 0) {
    //插入时
    $("#file").focus();
   }
  });
 function doExamine(id,state){
  AjaxRequest.submit("examine.save", {
   "id" : id,state:state
  }, "${ctx}/project/document/list.view");
 }
</script>
 </template:put>

 <!-- 指定表单内容 -->
 <template:put name="form">
  <!-- form的名称固定为mainForm -->
  <form name="inputForm" id="inputForm" action="${action}" method="post"
   enctype="multipart/form-data"><c:if
   test="${sessionScope.employee.priv==1 && document.dataState!=1}">
   <table class="form" cellspacing="1">
    <tr>
     <td width="120">资料截止日期<span class="notice">*</span></td>
     <td width="300" class="special"><input type="text"
      class="required text" name="endDate" id="endDate"
      value="<c:out value="${document.endDate}"/>"
      οnclick="setDay(this);" /></td>
     <td width="120">资料类型<span class="notice">*</span></td>
     <td width="300" class="special"><select name="docType"
      id="docType" title="请选择一个组" validate="required:true"
      style="width: 152px;">
      <option value="">请选择组</option>
      <c:forEach items="${docTypes}" var="dt">
       <c:choose>
        <c:when test="${document.docType==dt}">
         <option value="${dt}" selected="selected">${dt}</option>
        </c:when>
        <c:otherwise>
         <option value="${dt}">${dt}</option>
        </c:otherwise>
       </c:choose>
      </c:forEach>
     </select>
    </tr>

    <tr>
     <td>资料文档</td>
     <td colspan="3"><input type="file" class="required text"
      name="fileUpload" id="fileUpload" /></td>
    </tr>

    <tr>
     <td colspan="4" align="left" height="50px"><c:if
      test="${document.dataState==0 || document.dataState==3}">
      <input type="submit" class="submit" value=" 保存 " />
     </c:if> <input type="button" class="button" value="返回列表 "
      οnclick="window.location='${ctx}/project/document/list.view'" /></td>
    </tr>

   </table>
  </c:if> <c:if
   test="${sessionScope.employee.priv==2 || sessionScope.employee.priv==0 || (sessionScope.employee.priv==1 && document.dataState==1)}">
   <table class="main" cellspacing="1">

    <tr>
     <td class="desc">资料截止日期</td>
     <td width="300" class="special"><fmt:formatDate
      value="${document.endDate}" type="date" dateStyle="long" /></td>
     <td class="desc">资料类型</td>
     <td width="300" class="special">${document.docType}</td>
    </tr>

    <tr>
     <td class="desc">资料文档</td>
     <td colspan="3"><a href="${ctx}/${document.document}">下载文档</a></td>
    </tr>

    <tr>
     <td colspan="4" align="left" height="50px"><c:if
      test="${document.dataState==1 && sessionScope.employee.priv==2}">
      <input type="hidden" name="state" value="" id="state" />
      <input type="button" class="button" value="审批通过 "
       οnclick="doExamine(${document.id},2);" />
      <input type="button" class="button" value="审批不通过 "
       οnclick="doExamine(${document.id},3);" />
     </c:if> <input type="button" class="button" value="返回列表 "
      οnclick="window.location='${ctx}/project/document/list.view'" />
     </td>
    </tr>
   </table>
  </c:if> <input type="hidden" name="id" value="${document.id} " /></form>
 </template:put>

</template:insert>

下面是DocumentAction(采用spring的注释):

package com.ztev.fipmis.project;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.ztev.fipmis.BaseAction;
import com.ztev.fipmis.BaseService;
import com.ztev.fipmis.ServiceException;
import com.ztev.fipmis.SessionManager;
import com.ztev.fipmis.baseinfo.AdcdBean;
import com.ztev.fipmis.baseinfo.AdcdService;
import com.ztev.fipmis.baseinfo.EmployeeBean;
import com.ztev.fipmis.file.FileSystemSaver;
import com.ztev.fipmis.irrigation.util.AdcdIrUtil;
import com.ztev.pagination.PageParameterSimple;

/**
 * 项目文档信息操作控制器。
 *
 * @author 朱志国 (zhu.zhiguo@hotmail.com) *
 */
@Controller
@RequestMapping("/project/document/")
public class DocumentAction extends BaseAction {

 @InitBinder
 public void initBinder(WebDataBinder binder){
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  format.setLenient(false);
  binder.registerCustomEditor(Date.class,new CustomDateEditor(format, true));
 }
 /**
  * 项目文档处理业务实例
  */
 @Autowired
 private DocumentService documentService;


 @Autowired
 private AdcdService adcdService;

 /**
  * 显示列表,默认页面
  *
  * @param model
  * @param pp
  *            分页参数。
  * @param user
  *            查询条件
  * @return
  */
 @RequestMapping("list.view")
 public String showList(Model model, PageParameterSimple pp,
   Document document,HttpSession session,AdcdBean queryBean) {
  //请求为空
        if( StringUtils.isBlank(queryBean.getAdcd()) ){
         /** 取得用户上次查询的行政区划信息**/
         AdcdBean adcdBean = SessionManager.getQueryAdcdBean(session);
         /** 上次查询的行政区划信息为空,使用当前权限默认查询**/
         if( adcdBean == null ){
                //查找当前权限下所有Adcd
          EmployeeBean user = SessionManager.getEmployee(session);
                //找到当前权限默认查询
          BeanUtils.copyProperties(user, queryBean);
         }else{
          BeanUtils.copyProperties(adcdBean, queryBean);
         }
        }else{
         /** 保存用户查询的行政区划信息**/
         SessionManager.setQueryAdcdBean(session, queryBean);
        }

  //默认选中行政条件
  model.addAttribute("queryAdcd", queryBean);

  //用户查询行政区划
  List<AdcdBean> rightAdcdBeans = adcdService.findListBylike(queryBean.getAdcd());
  // 分页信息,名字固定为pageinfo
  model.addAttribute("pageinfo", this.documentService.findPage(pp,
    document,AdcdIrUtil.getAdcdsCodeStr(rightAdcdBeans)));
  model.addAttribute("documentQuery", document);
  return "project/document/documentList";

 }// end showList

 /**
  * 显示插入表单
  *
  * @param model
  * @return
  */
 @RequestMapping("insert.form")
 public String showInsert(Model model) {
  Document document = new Document();
  document.setDataState(0);
  model.addAttribute("docTypes", BaseService.findAllDocType());
  model.addAttribute("document", document);
  model.addAttribute("action", "insert.save");
  model.addAttribute("groups", "");
  return "project/document/documentForm";

 }// end showInsert

 /**
  * 显示修改页面
  *
  * @param userId
  *            用户唯一标识。
  * @param model
  * @return
  */
 @RequestMapping("update.form")
 public String showUpate(@RequestParam("id") Integer documentId,
   HttpSession session, Model model) {
  Document document = this.documentService.find(documentId);
  EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
  if (user.getPriv() == 2) {
   model.addAttribute("action", "examine.save");
  } else if (user.getPriv() == 1) {
   model.addAttribute("action", "update.save");
  }
  model.addAttribute("docTypes", BaseService.findAllDocType());
  model.addAttribute("document", document);
  model.addAttribute("action", "update.save");
  model.addAttribute("groups", "");
  return "project/document/documentForm";
 }// end showUpate

 /**
  * 执行插入
  *
  * @param user
  * @return
  */
 @RequestMapping("insert.save")
 public void saveInsert(Document document, HttpServletResponse response,
   DefaultMultipartHttpServletRequest request,HttpSession session) throws Exception {
  MultipartFile multipartFile = document.getFileUpload();
  FileSystemSaver saver = new FileSystemSaver();
  Document docut = saver.save(multipartFile,request);
  document.setDocument(docut.getDocument());
  document.setName(docut.getName());
  EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
  document.setInputTime(new Date(System.currentTimeMillis()));
  document.setAdcd(user.getAdcd());
  document.setDataState(0);
  document.setInputEmpNo(user.getEmpNo());
  try {
   this.documentService.insert(document);
   super.printJson(response, true);
  } catch (ServiceException se) {
   super.printJson(response, false, se.getMessage());
  }
 }// end saveInsert


 @RequestMapping("download.view")
 public void showdDwnload(@RequestParam("id") Integer id,HttpServletResponse response,HttpServletRequest request) throws Exception {
  Document document = documentService.find(id);
  try {
   //document.setDocument(request.getRequestURL().toString().replaceAll(request.getRequestURI(), "")+ request.getContextPath()+document.getDocument());
   FileSystemSaver saver = new FileSystemSaver();
   saver.download(response, document,request);
  } catch (ServiceException se) {

  }

 }// end saveInsert

 /**
  * 执行更新。
  *
  * @param user
  * @return
  */
 @RequestMapping("update.save")
 public void saveUpdate(Document document, HttpServletResponse response,
   DefaultMultipartHttpServletRequest request) throws Exception {
  MultipartFile multipartFile = document.getFileUpload();
  FileSystemSaver saver = new FileSystemSaver();
  if (multipartFile!=null) {
   Document docut = saver.save(multipartFile,request);
   document.setDocument(docut.getDocument());
  }
  this.documentService.update(document);
  super.printJson(response, true);

 }// end saveUpdate

 /**
  * 执行更新。
  *
  * @param userId
  *            用户唯一标识。
  * @return
  */
 @RequestMapping("delete.save")
 public void saveDelete(Integer id, HttpServletResponse response,HttpServletRequest request)
   throws Exception {
  try {
   String url=documentService.find(id).getDocument();
   this.documentService.delete(id);
   FileSystemSaver saver = new FileSystemSaver();
   saver.delete(url, request);
   super.printJson(response, true);

  } catch (ServiceException se) {
   super.printJson(response, false, se.getMessage());
  }

 }// end saveDelete

 /**
  * 提交审批。
  *
  * @param userId
  * 用户唯一标识。
  * @return
  */
 @RequestMapping("examine.save")
 public void saveExamine(@RequestParam("id") Integer id,
   @RequestParam("state") Integer state, HttpServletResponse response,
   HttpServletRequest request,HttpSession session) throws Exception {
  try {
   EmployeeBean user = (EmployeeBean)SessionManager.getEmployee(session);
   Document document = documentService.find(id);
   if (document.getDataState() == 0) {
    document.setDataState(1);
   } else {
    document.setDataState(state);
    document.setApproveTime(new Date(System.currentTimeMillis()));
    document.setApproveEmpNo(user.getEmpNo());
   }
   this.documentService.examine(document);
   super.printJson(response, true);
  } catch (ServiceException se) {
   super.printJson(response, false, se.getMessage());

  }

 }// end saveDelete

}

以下是DocumentService:

package com.ztev.fipmis;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 业务操作的基类。
 *
 * @朱志国 (zhu.zhiguo@hotmail.com) *
 */
public class BaseService {

 /**资金类别(来源)的类型标识*/
 public static final String TYPE_DOC_TYPE = "document-type";
 
 /**建设属性*/
 public static final String IRBUILD_BEAN= "irbuild-bean";
 
 /** 投资部门分类*/
 public static final String INVERT_DEPT= "invest-Dept";
 
 /**
  * 日志操作句柄
  */
 protected Log logger = LogFactory.getLog(getClass());
 
 public static String[] findAllDocType(){
  return BaseDataHelper.getValues(TYPE_DOC_TYPE);
 }
 
 public static Map<String, String> findIrbuildDec(){
  return BaseDataHelper.getKeyDescriptionMap(IRBUILD_BEAN);
 }
 
 public static Map<String, String> findIrbuildValue(){
  return BaseDataHelper.getKeyValueMap(IRBUILD_BEAN);
 }
 
 public static String[] findInvestDepart(){
  return BaseDataHelper.getValues(INVERT_DEPT);
 }
 
 public static  Map<String, String> findInvDepDscription(){
  return BaseDataHelper.getKeyDescriptionMap(INVERT_DEPT);
 }
 
 public static BaseDataEntry[] findAllInvertDept(){
  return BaseDataHelper.getEntries(INVERT_DEPT);
 }
 
 public static Map<String, String> findInvertDeptValue(){
  return BaseDataHelper.getKeyValueMap(INVERT_DEPT);
 }
 
}
以下是 FileSystemSaver :

package com.ztev.fipmis.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.ztev.fipmis.ConfigManager;
import com.ztev.fipmis.StringUtils;
import com.ztev.fipmis.project.Document;

/**
 * 将文档保存在文件系统中
 *
 * @author 李飞飞
 */
public class FileSystemSaver {

 /**
  * 判断该类型文件是否允许上传
  *
  * @param file
  * @return
  */
 protected boolean accept(String fileName) {
  String filesDenied = ConfigManager.getProperty(ConfigManager.KEY_FILES_DENIED);
  if (filesDenied == null)
   return true;
  StringTokenizer st = new StringTokenizer(filesDenied, ",");
  while (st.hasMoreElements()) {
   if (fileName.equalsIgnoreCase(st.nextToken()))
    return false;
  }
  return true;
 }
 
 /**
  * 下载文件方法
  * @param response
  * @param path 文件地址
  * @param name 文件名
  * @throws IOException
  */
 public void download(HttpServletResponse response,Document document,HttpServletRequest request) throws IOException{
  String fileName =  new String(document.getName().getBytes("GBK"),"ISO8859-1");
  response.setContentType( document.getDocType() ); //或gif等
  response.setHeader("Content-Disposition", "attachment;filename=" +fileName);
  //获取欲下载的文件输入流
  String uploadPath = this.getUploadPath(request);
  String baseURI = this.getPhotoBaseURI();
  String path=uploadPath+ StringUtils.replace(document.getDocument().substring(baseURI.length()), "/",File.separator);
  FileInputStream fis = new FileInputStream(path);
  BufferedInputStream bis = new BufferedInputStream(fis);
  FileCopyUtils.copy(bis, response.getOutputStream());
 
  response.getOutputStream().flush();
  response.getWriter().flush();
  response.getWriter().close();
 }
 
 /**
  * 保存文件方法
  *
  * @param imgFile
  * @param fileName
  * @param autoRotate
  * @param context
  * @return
  * @throws IOException
  */
 @SuppressWarnings("null")
 public Document save(MultipartFile file, DefaultMultipartHttpServletRequest request)
   throws IOException {
  Document document = new Document();
  System.out.println("-----------得到文件名称--------"+file.getOriginalFilename()+"---------4--------");
  //file.getOriginalFilename()得到文件名称(加后缀)而 getFileExtend得到文件的后缀名
  String extendName = getFileExtend(file.getOriginalFilename());
  System.out.println("-----------得到文件--------"+extendName+"---------6--------");
  String[] urls = this.createNewPhotoURI(extendName, request);
  if (urls == null && urls.length == 0)
   return null;

  String origionalPath = urls[0];
  System.out.println("-----------7--------"+origionalPath+"---------7--------");
  // 保存上传的文件
  {
   writeToFile(file, origionalPath);
  }

  // 计算图片的url
  String uploadPath = this.getUploadPath(request);
  System.out.println("------------5-----------"+uploadPath+"------------5--------");
  //得到图片在文件夹的完整名称
  String path = origionalPath.substring(uploadPath.length());
  System.out.println("------------6-----------"+path+"------------6--------");
  document.setDocument(getPhotoBaseURI()+ StringUtils.replace(path, File.separator, "/"));
  System.out.println("------------8-----------"+getPhotoBaseURI()+"------------8--------");
  document.setDocType(extendName);
  document.setName(file.getOriginalFilename());
  System.out.println("------------9-----------"+file.getOriginalFilename()+"------------9--------");
  System.out.println(document.getDocument());
  return document;
 }

 /**
  * 判断是否为合法的文档
  *
  * @param extendName
  * @return
  */
 public static boolean isImage(String extendName) {
  return "doc".equalsIgnoreCase(extendName)
    || "rar".equalsIgnoreCase(extendName)
    || "xls".equalsIgnoreCase(extendName)
    || "ppt".equalsIgnoreCase(extendName)
    || "txt".equalsIgnoreCase(extendName)
    || "pdf".equalsIgnoreCase(extendName);
 }
 
 /**
  * 获取文件类型
  * @param fn
  * @return
  */
 public  String getFileExtend(String fn){
  if(StringUtils.isEmpty(fn))
   return null;
  int idx = fn.lastIndexOf('.')+1;
  if(idx==0 || idx >= fn.length())
   return null;
  return fn.substring(idx);
 }

 /**
  * 将上传的保存到磁盘中
  * 文件
  * @param imgFile
  * @param origionalPath
  * @throws IOException
  */
 public static void writeToFile(MultipartFile multifile, String origionalPath)
   throws IOException {
  File file=new File(origionalPath);
  // 保存上传的文件
  FileUtils.writeByteArrayToFile(file,multifile.getBytes());
 }

 /*
  * (non-Javadoc)
  *
  * @see com.liusoft.dlog4j.photo.PhotoSaver#delete(java.lang.String)
  */
 public boolean delete(String imgURL, HttpServletRequest context)
   throws IOException {
  String uploadPath = this.getUploadPath(context);
  String baseURI = this.getPhotoBaseURI();
  String path = uploadPath
    + StringUtils.replace(imgURL.substring(baseURI.length()), "/",
      File.separator);
  File f = new File(path);
  if (f.exists() && f.isFile())
   return f.delete();
  return false;
 }

 /**
  * 检测与创建一级、二级文件夹、文件名 这里我通过传入的两个字符串来做一级文件夹和二级文件夹名称
  * 通过此种办法我们可以做到根据用户的选择保存到相应的文件夹下
  */
 public File creatFolder(String typeName, String brandName, String fileName) {
  File file = null;
  typeName = typeName.replaceAll("/", ""); // 去掉"/"
  typeName = typeName.replaceAll(" ", ""); // 替换半角空格
  typeName = typeName.replaceAll(" ", ""); // 替换全角空格

  brandName = brandName.replaceAll("/", ""); // 去掉"/"
  brandName = brandName.replaceAll(" ", ""); // 替换半角空格
  brandName = brandName.replaceAll(" ", ""); // 替换全角空格

  File firstFolder = new File("c:/" + typeName); // 一级文件夹
  if (firstFolder.exists()) { // 如果一级文件夹存在,则检测二级文件夹
   File secondFolder = new File(firstFolder, brandName);
   if (secondFolder.exists()) { // 如果二级文件夹也存在,则创建文件
    file = new File(secondFolder, fileName);
   } else { // 如果二级文件夹不存在,则创建二级文件夹
    secondFolder.mkdir();
    file = new File(secondFolder, fileName); // 创建完二级文件夹后,再合建文件
   }
  } else { // 如果一级不存在,则创建一级文件夹
   firstFolder.mkdir();
   File secondFolder = new File(firstFolder, brandName);
   if (secondFolder.exists()) { // 如果二级文件夹也存在,则创建文件
    file = new File(secondFolder, fileName);
   } else { // 如果二级文件夹不存在,则创建二级文件夹
    secondFolder.mkdir();
    file = new File(secondFolder, fileName);
   }
  }
  return file;
 }

 public InputStream read(String imgURL, HttpServletRequest context)
   throws IOException {
  String uploadPath = this.getUploadPath(context);
  String baseURI = this.getPhotoBaseURI();
  String path = uploadPath
    + StringUtils.replace(imgURL.substring(baseURI.length()), "/",
      File.separator);
  File f = new File(path);
  if (f.exists() && f.isFile())
   return new FileInputStream(f);
  return null;
 }

 public OutputStream write(String imgURL, HttpServletRequest context)
   throws IOException {
  String uploadPath = this.getUploadPath(context);
  String baseURI = this.getPhotoBaseURI();
  String path = uploadPath
    + StringUtils.replace(imgURL.substring(baseURI.length()), "/",
      File.separator);
  File f = new File(path);
  if (f.exists() && f.isFile())
   return new FileOutputStream(f, false);
  return null;
 }

 /**
  * 生成一个用于存储文件并返回其URI地址
  *
  * @param ctx
  * @param ext
  *            例如: .gif
  * @return
  * @throws IOException
  */
 private String[] createNewPhotoURI(String ext, HttpServletRequest context)
   throws IOException {
  Calendar cal = Calendar.getInstance();
  StringBuffer dir = new StringBuffer();
  dir.append(getUploadPath(context));
  System.out.println("------------10-----------"+getUploadPath(context)+"------------10--------");
  dir.append(cal.get(Calendar.YEAR));
  System.out.println("------------11-----------"+dir.toString()+"------------11--------");
  dir.append(File.separator);
  System.out.println("------------12-----------"+dir.toString()+"------------12--------");
  dir.append(cal.get(Calendar.MONTH) + 1);
  dir.append(File.separator);
  dir.append(cal.get(Calendar.DATE));
  dir.append(File.separator);
  System.out.println("------------13-----------"+dir.toString()+"------------13--------");
  File file = new File(dir.toString());
  if (!file.exists()) {
   // 如果目录不存在则创建目录
   synchronized (FileSystemSaver.class) {
    if (!file.mkdirs())
     return null;
   }
  }
  file = null;
  int times = 0;
  do {
   // 生成独一无二的文件名
   String fn = String.valueOf(System.currentTimeMillis()) + '.' + ext;
   System.out.println("------------14-----------"+fn+"------------14--------");
   StringBuffer fn_preview = new StringBuffer();
   fn_preview.append(System.currentTimeMillis());
   fn_preview.append("_s.");
   fn_preview.append(ext);
   File f = new File(dir + fn);
   File f_preview = new File(dir + fn_preview.toString());
   System.out.println("------------15-----------"+dir + fn_preview.toString()+"------------15--------");
   if (!f.exists() && !f_preview.exists()) {
    try {
     if (f.createNewFile())
      return new String[] { dir + fn,
        dir + fn_preview.toString() };
    } catch (SecurityException e) {
    } catch (IOException e) {
    } finally {
     f = null;
     f_preview = null;
    }
   }
   times++;
  } while (times < 10);

  return null;
 }

 /**
  * 返回保存文件的物理路径
  *
  * @param ctx
  * @return
  */
 private String getUploadPath(HttpServletRequest context) {
  if (upload_path != null){
   System.out.println("----------1-----------"+upload_path+"---------1--------");
   return upload_path;     
  }
  String dir = ConfigManager.getProperty(ConfigManager.KEY_FILE_BASE_URI);
  System.out.println("----------2-----------"+dir+"---------2--------");
  if (dir.startsWith("file://"))
   upload_path = dir.substring("file://".length());
  else if (dir.startsWith("/"))
   upload_path = context.getSession().getServletContext().getRealPath(dir);
  else
   upload_path = dir;
  if (!upload_path.endsWith(File.separator))
   upload_path += File.separator;
        System.out.println("------------3---------"+upload_path+"----------3-------");
  return upload_path;
 }

 /**
  * 返回文件对应的BaseURL
  *
  * @param ctx
  * @return
  */
 private String getPhotoBaseURI() {
  if (upload_uri != null)
   return upload_uri;
  upload_uri = ConfigManager.getProperty(ConfigManager.KEY_FILE_BASE_URI);
  if (!upload_uri.endsWith("/"))
   upload_uri += '/';
  return upload_uri;
 }

 private String upload_path = null;
 private String upload_uri = null;

}

这些就可以完成正常的上传下载的功能啦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值