JAVA struts2 上传和下载

来源:互联网 发布:挖掘社交网络 中文版 编辑:程序博客网 时间:2024/05/16 01:50
//下载
public class DownLoadAction extends ActionSupport {
private final static String DOWNLOADFILEPATH="/upload/";
private String fileName;

public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}

public InputStream getInputStream(){
InputStream in;

in= ServletActionContext.getServletContext().getResourceAsStream(DOWNLOADFILEPATH+fileName);
System.out.println(DOWNLOADFILEPATH+fileName);
System.out.println(in);
return in;
}
public String getDownloadChineseFileName(){
String downloadChineseFileName=fileName;

try{
downloadChineseFileName=new String (downloadChineseFileName.getBytes(),"ISO8859-1");
System.out.println(downloadChineseFileName);
}catch(UnsupportedEncodingException e){
e.printStackTrace();

}
System.out.println(downloadChineseFileName);
return downloadChineseFileName;
}
@Override
public String execute()  {
// TODO Auto-generated method stub
return SUCCESS;
}
}


//上传

public class UploadAction extends ActionSupport {
private final static String UPLOADDIR="/upload";
private List<File>file;
private List<String>fileFileName;
private List<String>fileContenType;
public List<File> getFile() {
return file;
}
public void setFile(List<File> file) {
this.file = file;
}
public List<String> getFileFileName() {
return fileFileName;
}
public void setFileFileName(List<String> fileFileName) {
this.fileFileName = fileFileName;
}
public List<String> getFileContenType() {
return fileContenType;
}
public void setFileContenType(List<String> fileContenType) {
this.fileContenType = fileContenType;
}

@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
for(int i=0;i<file.size();i++){
upLoadFile(i);

}
return "success";
}
private void upLoadFile(int i)throws FileNotFoundException,IOException{
try{
InputStream in =new FileInputStream(file.get(i));
String dir=ServletActionContext.getRequest().getRealPath(UPLOADDIR);
System.out.println(dir);
File uploadFile=new File(dir,this.getFileFileName().get(i));
OutputStream out=new FileOutputStream(uploadFile);

byte[]buffer=new byte[104*1024];
int length;
while((length=in.read(buffer))>0){
out.write(buffer, 0, length);
}

}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}