日期:2014-05-20  浏览次数:20725 次

java下载文件问题
用java流下载txt文件,通过report_download.action请求去下载弹出保存框中文件名是report_download.action,且能打开是在ie中直接打开,不能进行保存是什么原因???

------解决方案--------------------
五码无真相。
------解决方案--------------------
我做过类似的,你配置有问题吧,我给你找找代码
------解决方案--------------------
Java code

response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF8").replace("+", "%20") + "\"");

------解决方案--------------------
"UTF8"->"UTF-8"
------解决方案--------------------
既然能出来文件下载框,怎么会不能打开或者保存呢。。。

出来框后好像就是windows干的事了吧。
------解决方案--------------------
这是下载请求action,前台传过来文件名和路径即可,
Java code

package com.oemp.audi.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

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

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.oemp.frame.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;

@Scope("prototype")
@Controller("audi.action.DownloadAction")
public class DownloadAction extends BaseAction {
    private String fileName;// 文件名
    private String filePath;// 文件路径

    public String getFilePath() {
    return filePath;
    }

    public void setFilePath(String filePath) {
    this.filePath = filePath;
    }

    public String getFileName() {

    return fileName;
    }

    public void setFileName(String fileName) {
    this.fileName = fileName;
    }

    private String filenameInCN;

    public String getFilenameInCN() {
    return filenameInCN;
    }

    public void setFilenameInCN(String filenameInCN) {
    try {
        this.filenameInCN = new String(filenameInCN.getBytes(),
            "ISO-8859-1");
    } catch (Exception e) {
        e.printStackTrace();
    }
    }

    /**
     * 返回与下载的文件流
     * 
     * @return
     * @throws Exception
     */
    public InputStream getDownloadFile() throws Exception {
    this.setFilenameInCN(fileName);
    return ServletActionContext.getServletContext().getResourceAsStream(
        filePath + fileName);
    }

    /**
     * 下载文件之前执行的方法(本方法检测了文件是否存在)
     */
    public String execute() {
    try {
        fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    String path = request.getRealPath(filePath + fileName);
    File file = new File(path);
    if (!file.exists()) {
        return super
            .renderHtmlGBK("<script> alert('文件失效了!可能原因是:文件被移动位置了,或者文件名发生了变化!');history.go(-1);</script>");
    }
    return SUCCESS;
    }
}