struts文件上传和下载

1.上传文件(action中)

public class uploadAction extends ActionSupport{
private File[] photo;
private String[] photoFileName;
private String savepath = "/upload";
public File[] getPhoto() {
return photo;
}
public void setPhoto(File[] photo) {
this.photo = photo;
}
public String[] getPhotoFileName() {
return photoFileName;
}
public void setPhotoFileName(String[] photoFileName) {
this.photoFileName = photoFileName;
}
public String getSavepath() {
return savepath;
}
public void setSavepath(String savepath) {
this.savepath = savepath;
}
public String upload() {
// reader 字符输入流
// writer 字符输出流
try {
for(int i=0;i<photo.length;i++){
FileInputStream fis = new FileInputStream(photo[i]);// 字节输入流
// 获取savapath输出的文件夹在服务器磁盘上的真实路径
String path = ServletActionContext.getServletContext().getRealPath(
savepath);
File savafile = new File(path, photoFileName[i]);
if (savafile.createNewFile()) {
FileOutputStream fos = new FileOutputStream(savafile);// 字节输出流
// 复制fis的内容到fos中
IOUtils.copy(fis, fos);
fos.close();
}
fis.close();
}
return SUCCESS;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ERROR;
}
}

2.下载文件(action中)

public class downloadAction extends ActionSupport{
       public String filename;
       public InputStream is;
       private long length;
       private String downloadPath="/upload";
       public String download(){
      try {
//获取下载文件的路径
  String path=ServletActionContext.getServletContext().getRealPath(downloadPath);
  File downloadFile=new File(path,filename);
  if(downloadFile.exists()){//文件存在否?
is=new FileInputStream(downloadFile);
//获取文件长度
length=downloadFile.length();
return SUCCESS;
  }
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      return ERROR;
       }
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public InputStream getIs() {
return is;
}
public void setIs(InputStream is) {
this.is = is;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
/*public String getDownloadPath() {
return downloadPath;
}
public void setDownloadPath(String downloadPath) {
this.downloadPath = downloadPath;
}*/
       
}


3.前台页面

<s:form method="post" action="photo" enctype="multipart/form-data">
   <s:file name="photo" label="选择文件"></s:file>
   <s:file name="photo" label="选择文件"></s:file>
    <s:submit value="上传"></s:submit>
   </s:form>
   <a href="download.jsp">下载文件</a>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值