Java实现文件下载讲解

前台是用GWT写的获取请求服务器端的地址方法:

 

 private void getAddress() {
        ModifyCurrentPasswordService.Util.getInstance().getServerPath(new AsyncCallback<String>() {

            public void onFailure(Throwable exception) {
                ExceptionHandler.handle(exception);
            }

            public void onSuccess(String path) {
                downLoad(path);
            }
        });
    }

  

  定义的方法有两个接口一个实现类: 接口1.ModifyCurrentPasswordService

 

public interface ModifyCurrentPasswordService extends RemoteService {
    public ResultMessage  modifyCurrentPassword(String oldPass,String newPass,String userId);

    public String getServerPath();
    public static class Util {
        private static ModifyCurrentPasswordServiceAsync instance;

        public static ModifyCurrentPasswordServiceAsync getInstance() {
            if (instance == null) {
                instance = (ModifyCurrentPasswordServiceAsync) GWT.create(ModifyCurrentPasswordService.class);
                ServiceDefTarget target = (ServiceDefTarget) instance;
                target.setServiceEntryPoint(GWT.getModuleBaseURL() + "gwt-services/modifyCurrentPassword-service");
            }
            return instance;
        }
    }

}

 

 

接口2.ModifyCurrentPasswordServiceAsync

public interface ModifyCurrentPasswordServiceAsync {
    public void  modifyCurrentPassword(String oldPass,String newPass,String userId, AsyncCallback<ResultMessage> callback);

    public void getServerPath(AsyncCallback<String> callback);

}

  

实现类ModifyCurrentPasswordServiceImpl 

 

public class ModifyCurrentPasswordServiceImpl extends RemoteServiceServlet implements ModifyCurrentPasswordService {

    /**
     * @author 
     * @since 2009-7-30
     */
    private static final long serialVersionUID = 7889155041042199323L;

    private static Logger log = Logger.getLogger(ModifyCurrentPasswordServiceImpl.class);

    private UserBizFacade userBizFacade;
    
    private  String address;

    public ResultMessage modifyCurrentPassword(String oldPass, String newPass, String userId) {
        ResultMessage message = new ResultMessage();
        try {
            UserDto userDto = null;
            if (userId != null) {
                log.debug("-------------------------------------------"+userId);
                userDto = this.userBizFacade.findUserById(Integer.parseInt(userId));
                // 解密
                DESEncry des = DESEncry.init();
                String originPass = des.ClsDESCode(userDto.getPin());
                if (originPass.compareTo(oldPass) == 0) {
                    // 加密
                    String newEncCode = des.ClsEncCode(newPass);
                    if (userDto != null) {
                        userDto.setPin(newEncCode);
                        update(userDto);
                        message.setResultMsg("success");
                    } else {
                        message.setResultMsg("failure");
                    }
                } else {
                    message.setResultMsg("error");
                }
            } else
                message.setResultMsg("failure");

        } catch (Exception e) {

        }
        return message;
    }

    private   synchronized    void update(UserDto userDto) {
        this.userBizFacade.saveUser(userDto, null);
    }

    public UserBizFacade getUserBizFacade() {
        return userBizFacade;
    }

    public void setUserBizFacade(UserBizFacade userBizFacade) {
        this.userBizFacade = userBizFacade;
    }

    public String getServerPath() {
        String realpath="";
        address=ModifyCurrentPasswordServiceImpl.class.getClassLoader().getResource(String.valueOf(File.separatorChar)).getPath();
        String path[]=address.split("/WEB-INF");
        realpath=path[0]+"/doc";
        log.debug("realpath is"+realpath);
        return realpath;
    }
}

 

 

 

 发送请求的方法

private void downLoad(String path) {
        /*
         * Linux下文件路径需要加"/"
         * Windows下不需要加"/"
         */
        String address = "";
        if (sign.equals("service")) {
            path = path + "/AiXinFuWuTaiCaoZuoShuoMing.doc";
        } else if (sign.equals("sale")) {
            path = path + "/AiXinXiaoShouCaoZuoShuoMing.doc";
        } else {
            path = path + "/AiXinXiaoZhiJianCaoZuoShuoMing.doc";
        }
        if (path.substring(0, 1).equals("/")) {
            address = path.substring(1);
        } else {
            address = path;
        }
        Location.replace(GWT.getHostPageBaseURL() + "fileDownLoadController?address=" + address);
    }

  

 

 

 rpc调用请求配置 请求地址的配置

web.xml

 

<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/fileDownLoadController</url-pattern>
    </servlet-mapping>
     <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/downloadCreateCardFiled</url-pattern>
    </servlet-mapping>
    

  

dispatcher-servlet.xml

 <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
               
        <property name="mappings">
        	<props>
            	<prop key="/fileDownLoadController">helpDownLoadController</prop>
            	<prop key="/downloadCreateCardFiled">creationFileDownloadController</prop>
        	</props>
        </property>
    </bean>


 <bean id="creationFileDownloadController" class="com.***.crs.gxt.server.service.CardCreationFileDownloadController"></bean>

 <bean id="helpDownLoadController"  class="com.***.loveJewelry.ui.indexLovo.server.service.FileDownLoadController"/>

 

 

 

 

 从服务器端读写到本地硬盘FileDownLoadController类

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

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

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class FileDownLoadController implements Controller {
    private static final Log log = LogFactory.getLog(FileDownLoadController.class);

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String address = request.getParameter("address");
        log.debug("address of request is " + address);
        if (null == address) {
            return null;
        }
        String fileName=address.substring(address.lastIndexOf("/")+1);
        File file=new File(address);
        response.setContentType("application/x-msdownload");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        OutputStream  out;
        FileInputStream  fis=null;
        try{
            out=response.getOutputStream();
            fis=new FileInputStream(file);
            IOUtils.copy(fis, out);
            IOUtils.closeQuietly(fis);
        }
        catch (IOException e) {
            log.error("Unexpected exception occurred", e);
            IOUtils.closeQuietly(fis);
        }
        return null;
    }

}

  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值