java实现文件下载功能
点击下载后,后台的代码是怎么实现的,哪位大哥给个例子或者指点迷津,谢谢。
[解决办法]
package com.cn.Action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream.GetField;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
private String title;
private File myfile;
private String myfileContentType;
private String myfileFileName;
private String resultMsg;
private String allowExtensions;
private int maxSize;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public File getMyfile() {
return myfile;
}
public void setMyfile(File myfile) {
this.myfile = myfile;
}
public String getMyfileContentType() {
return myfileContentType;
}
public void setMyfileContentType(String myfileContentType) {
this.myfileContentType=myfileContentType.substring(myfileContentType.indexOf("\")+1);
}
public String getMyfileFileName() {
return myfileFileName;
}
public void setMyfileFileName(String myfileFileName) {
this.myfileFileName = myfileFileName;
}
public String getResultMsg() {
return resultMsg;
}
public void setAllowExtensions(String allowExtensions) {
this.allowExtensions = allowExtensions;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
/* (non-Javadoc)
* @see com.opensymphony.xwork2.ActionSupport#execute()
*/
@Override
public String execute() throws Exception {
if(this.isAllowExtension(myfileFileName)){
if(myfile.length() > this.maxSize){
this.resultMsg = "上传的文件超过了"+(this.maxSize/(1024*1024)+"M");
return INPUT;
}else{
String path = ServletActionContext.getServletContext().getRealPath("/uploads");
FileOutputStream fos = new FileOutputStream(path+File.separator+getMyfileFileName());
FileInputStream fis = new FileInputStream(getMyfile());
byte [] by = new byte[1024];
int lent = 0;
while((lent=fis.read(by))!=-1){
fos.write(by, 0, lent);
}
//如果为空就关闭流
if(fos!=null){
fos.flush();
fos.close();
}if(fis!=null){
fis.close();
}
return SUCCESS;
}
}else{
this.resultMsg = "不允许上传该格式的文件";
return INPUT;
}
}
/**
*
* @param filename 上传的文件名带后缀
* @return true--表示允许上传的文件,false--不许上传的文件
*/
public boolean isAllowExtension(String filename){
String[] allows = this.allowExtensions.split(";");
String extension = filename.substring(filename.lastIndexOf(".")+1);
for (String string : allows) {
if(string.equalsIgnoreCase(extension))
return true;
}
return false;
}
}
注明:这是struts2编写的 配置文件什么的和其他的struts2配置没什么区别 关键就是java代码里的