java 文件下载次数问题
做了一个文件下载功能,可是当我点击那个下载链接的时候,文件实际上已经下载了,下载次数加1了,点击下载链接之后,弹出下载对话框,点击下载,那一段下载有关的程序又被执行了一次,下载次数又加1了。
package com.cothink.lsys.action.exam;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ExamFileAction extends ActionSupport{
private String filename;
private String filetype;
private String fileid;
public InputStream getDownload()throws Exception{
filename=java.net.URLDecoder.decode(filename,"utf8");
HttpServletResponse response=ServletActionContext.getResponse();
OutputStream o=response.getOutputStream();
byte b[]=new byte[500];
File fileLoad=new File("F:/LearningSys/trunk/src/LearningSys/WebRoot/downloadmaterial/",fileid+"."+filetype);
response.setHeader( "Content-Disposition", "attachment;filename=" + new String( filename.getBytes("gb2312"), "ISO8859-1" )+"."+filetype);
long fileLength=fileLoad.length();
String length=String.valueOf(fileLength);
response.setHeader("Content_Length",length);
FileInputStream in=new FileInputStream(fileLoad);
int n=0;
while((n=in.read(b))!=-1){
String file_str=new String(b);
System.out.println(file_str);
o.write(b,0,n);
}
o.flush();
o.close();
in.close();
o = null;
return in;
}
@Override
public String execute() {
try {
this.filename= new String(filename.getBytes("iso-8859-1"),"utf-8");
this.filetype= new String(filetype.getBytes("iso-8859-1"),"utf-8");
this.fileid= new String(fileid.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
FileInputStream in=(FileInputStream)getDownload();
} catch (Exception e) {
e.printStackTrace();
}
ExamMaterial dlm= new ExamMaterial();
System.out.println("downloadTimes begin!!!!!");
dlm.downloadTimes(fileid);
return SUCCESS;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getFiletype() {
return filetype;
}
public void setFiletype(String filetype) {
this.filetype = filetype;
}
public String getFileid() {
return fileid;
}
public void setFileid(String fileid) {
this.fileid = fileid;
}
}
意思是点击下载链接程序执行execute ,但是弹出的对话框点下载之后execute 又被执行了一次,下载次数加2 了。我想实现的是点下载链接不执行程序,只有下载成功了,才让次数加1.急!!!! java 文件下载
[解决办法]
我觉得这个是业务逻辑的处理,跟你那段下载的代码没关系,
首先有三张表:用户表(user), 资源表(res), 下载表(download, 分别引用user和res)
点击下载后,如果download中不存在user和res关联的记录,就插入一条记录,已经存在就更新下载时间
然后再根据res的id去download中统计下载的次数,就好了
[解决办法]
刚刚测试了下,csdn下载也是点击时就插入数据了,不会管你下载成功与否(测试结果)。好像还没下载成功返回的函数吧,所有只能算点击次数,确实csdn可能只算了一次(后台不清楚),而且我的积分也扣了,,有点坑吧。。。LZ你的问题如果要成功才添加次数,要就要io流读取完一个文件后+1就可以了
[解决办法]
那你再做个界面吧,当你第一次点击时链接到一个action,在此action使下载量增一,
然后将文件数据 request到新做的界面 ,新页面设个submit 将数据提交至你的ExamFileAction
在此action 就不要对数据库 进行操作了