首页 > 代码库 > 文件下载

文件下载

不要再说用<a>标签下载了,这个会把文件打开而不是下载

例如:

 <a href="E:\MyDesktop\37fecd65330184de67d419a8d02e7081.jpg">下载</a>

如果我这样写,浏览器就会把图片直接打开,除非是一个浏览器打不开的文件

所以我们还是要用到java本身的文件读写来进行文件的下载

<a href="downloadFile?filename=<s:property value=http://www.mamicode.com/‘document_filename‘/>">下载</a>
package com.cpsec.tang.chemical.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

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

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
import com.cpsec.tang.chemical.biz.DocumentBiz;
import com.cpsec.tang.chemical.entity.Document;
import com.cpsec.tang.chemical.util.Pager;
import com.opensymphony.xwork2.ActionSupport;

@Controller("documentAction")
public class DocumentAction extends ActionSupport{private String filename;
    public String downloadFile(){
        System.out.println(filename);
        try {
            HttpServletResponse response=ServletActionContext.getResponse();
            //设置文件MIME类型  
            response.setContentType(ServletActionContext.getServletContext().getMimeType(filename));  
            //设置Content-Disposition  
            response.setHeader("Content-Disposition", "attachment;filename="+filename);  
            //获取目标文件的绝对路径  
            String fullFileName = ServletActionContext.getServletContext().getRealPath("/files/" + filename);  
            //System.out.println(fullFileName);  
            //读取文件  
            InputStream in = new FileInputStream(fullFileName); 
            //读取目标文件,通过response将目标文件写到客户端
            OutputStream out = response.getOutputStream();  
            //写文件  
            int b;  
            while((b=in.read())!= -1)  
            {  
                out.write(b);  
            }  
            in.close();  
            out.close();  
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
   
}

文件上传:http://www.cnblogs.com/bunuo/p/upLoadFile.html

文件下载