Spring mvc 使用SpringMVC和OpenCSV jar下载CSV文件
我试图在我的jsp中单击下载按钮下载一个.csv文件。jsp代码如下所示Spring mvc 使用SpringMVC和OpenCSV jar下载CSV文件,spring-mvc,Spring Mvc,我试图在我的jsp中单击下载按钮下载一个.csv文件。jsp代码如下所示 <form:form method="POST" id="poCSVForm" action="downloadPoCsv" commandName="poCSVcmd" modelAttribute="poCSVcmd"> <div class="content"> <fieldset>
<form:form method="POST" id="poCSVForm"
action="downloadPoCsv" commandName="poCSVcmd" modelAttribute="poCSVcmd">
<div class="content">
<fieldset>
<legend>Page Name</legend>
<div>
<div class="contentpane">
<table>
<tr>
<td><button type="submit" value="Download" id="downId" class="dwnldbtn">Download</button>
<button type="button" class="exit smallbtn" value="Exit">Exit</button></td>
</tr>
</table>
</div>
</div>
</fieldset>
</div>
</form:form>
页面名称
下载
出口
那么我的控制器代码是这样的
@RequestMapping(value = "/downloadPoCsv", method = RequestMethod.POST)
public void doPoCsvDownload(
@ModelAttribute("poCSVcmd") PurchaseOrderCSVBean poCsvBean,
Map<String, Object> model, HttpServletRequest req,HttpServletResponse response) throws IOException {
CSVWriter writer = null;
String filepath = null;
try {
HttpSession session = req.getSession();
Session hsession = (Session) session
.getAttribute(MOLConstants.HIBERNATE_SESSION_KEY);
filepath = "purchaseOrder" + new Date().getTime() + ".csv";
ServletContext context = req.getServletContext();
String realPath = context.getRealPath("");
System.out.println("appPath = " + realPath);
// construct the complete absolute path of the file
String fullPath = realPath + "\\stuff\\" + filepath;
System.out.println("fullPath = " + fullPath);
File downloadFile = new File(realPath);
try {
if (!downloadFile.exists()) {
if (downloadFile.mkdir()) {
} else {
throw new RuntimeException("Could not create directory");
}
}
} catch (Exception e) {
throw new RuntimeException();
}
String mimeType = context.getMimeType(fullPath); // get MIME type of the file
if (mimeType == null) {
mimeType = "application/octet-stream"; // set to binary type if MIME mapping not found
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
List<PoCsvUploadView> csvDataList = poService.getPoCsvData(poCsvBean.getExp_ind(),poCsvBean.getStdt(),poCsvBean.getEnddt());
FileWriter fwriter = new FileWriter(fullPath);
writer = new CSVWriter(fwriter, ',', CSVWriter.NO_QUOTE_CHARACTER);
String[] header = new String[31];
header[0] = "COMPANY_CD";
.......
header[30] = "VENDOR_TYPE";
List<String[]> li = new ArrayList<String[]>();
li.add(header);
for (PoCsvUploadView group : csvDataList)
{
String[] arr = new String[31];
arr[0] = group.getCompany_cd();
.....
arr[30] = group.getVendor_type();
li.add(arr);
}
writer.writeAll(li);
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception >> ", e);
throw new CustomGenericException(
"Error occured while loading report!!");
}finally{
writer.flush();
writer.close();
}
}
@RequestMapping(value=“/downloadposv”,method=RequestMethod.POST)
公开下载(
@ModelAttribute(“poCSVcmd”)PurchaseOrderCSVBean poCsvBean,
映射模型、HttpServletRequest请求、HttpServletResponse响应)引发IOException{
CSVWriter writer=null;
字符串filepath=null;
试一试{
HttpSession session=req.getSession();
会话hsSession=(会话)会话
.getAttribute(molstants.HIBERNATE_会话_键);
filepath=“purchaseOrder”+新日期().getTime()+“.csv”;
ServletContext=req.getServletContext();
字符串realPath=context.getRealPath(“”);
System.out.println(“appPath=“+realPath”);
//构造文件的完整绝对路径
字符串fullPath=realPath+“\\stuff\\”+filepath;
System.out.println(“fullPath=“+fullPath”);
文件下载文件=新文件(realPath);
试一试{
如果(!downloadFile.exists()){
if(downloadFile.mkdir()){
}否则{
抛出新的RuntimeException(“无法创建目录”);
}
}
}捕获(例外e){
抛出新的RuntimeException();
}
字符串mimeType=context.getMimeType(fullPath);//获取文件的MIME类型
if(mimeType==null){
mimeType=“application/octet stream”;//如果未找到MIME映射,则设置为二进制类型
}
System.out.println(“MIME类型:+mimeType”);
//设置响应的内容属性
response.setContentType(mimeType);
response.setContentLength((int)downloadFile.length());
//设置响应的标题
字符串headerKey=“内容处置”;
String headerValue=String.format(“附件;文件名=\%s\”,downloadFile.getName());
response.setHeader(headerKey,headerValue);
List csvDataList=posservice.getPoCsvData(poCsvBean.getExp_ind(),poCsvBean.getStdt(),poCsvBean.getEnddt());
FileWriter fwriter=新的FileWriter(完整路径);
writer=新的CSVWriter(fwriter,,,CSVWriter.NO_QUOTE_字符);
字符串[]头=新字符串[31];
表头[0]=“公司光盘”;
.......
表头[30]=“供应商类型”;
List li=new ArrayList();
li.添加(标题);
for(PoCsvUploadView组:csvDataList)
{
字符串[]arr=新字符串[31];
arr[0]=group.getCompany_cd();
.....
arr[30]=group.getVendor_type();
li.add(arr);
}
作者:李;
}捕获(例外e){
e、 printStackTrace();
logger.error(“异常>>”,e);
抛出新的CustomGenericException(
“加载报告时出错!!”;
}最后{
writer.flush();
writer.close();
}
}
现在,当我点击下载按钮时,csv文件正在特定位置生成,即fullPath变量上。但该文件不是通过浏览器下载的,而是浏览器正在下载名为downloadPoCsv的文件(与控制器方法中的@RequestMapping完全相同),这是不需要的。你们能帮点忙吗。Thanx。是的,我使用的是OpenCsv jar。这里要明确的是,问题是spring MVC而不是OpenCsv,因为您的问题描述是您正在尝试下载一个文件,而它正在下载一个具有不同名称的文件 CodeJava有一个。试试看