因为需要的参数都直接写在这里面了,文件地址和文件的名字都可以通过参数传递过来也可以在数据库中获取,最好通过超链接或则重新打开浏览器窗口过来,Ajax可不可以没有尝试过。
//通过新打开的窗口链接
window.location.href="${ctx}/attach/down.vm?name='wang'"; //这里进行传值
//后台取值
String name = param.get("name").toString();
@RequestParam Map<String,Object> param 传过来的值都在这里面。
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/attach")
public class BaseAttachDownController extends HttpServlet {
private static final long serialVersionUID = 1L;
@RequestMapping(path = "down")
public void downloadFile(HttpServletResponse response,@RequestParam Map<String,Object> param) throws Exception {
//文件的绝对地址
String FilePath = "D:\\Program Files\\procedure\\procedure";
String FileName = "wang.txt";
FileName = new String(FileName.getBytes("iso8859-1"), "utf-8");
File file = new File(FilePath + "\\" + FileName);
if (!file.exists()) {
return ;
} else {
response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(FileName, "utf-8"));
// 读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(FilePath + "\\" + FileName);
// 创建输出流
OutputStream out = response.getOutputStream();
// 创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
// 循环将输入流中的内容读取到缓冲区中
while ((len = in.read(buffer)) > 0) {
// 输出缓冲区内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
// 关闭文件流
in.close();
// 关闭输出流
out.close();
}
}
}