struts1.2文件上传

jsp页面

 

<!--上传图片时,在当前页面显示图片 注意form中必须加 enctype="multipart/form-data"-->
<form action="XXX.do" enctype="multipart/form-data">
<input type="file" name="file" onpropertychange="document.all.imgBook.src='file:///'+this.value" />
     <div id="img">
      <img id="imgBook" style="WIDTH: 110px; HEIGHT: 154px" height="154" src="" width="110"/>
     </div> 
</form>

ActionForm


public class DownloadForm extends ActionForm {

 private String fileName;
 
 private FormFile file;

public FormFile getFile() {
  return file;
 }


 public void setFile(FormFile file) {
  this.file = file;
 }


 public String getFileName() {
  return fileName;
 }


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

}

 

Action
public class Download_AddAction extends Action {

 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  DownloadForm downloadForm = (DownloadForm) form;// TODO Auto-generated method stub
  
//  上传
    FormFile file = downloadForm.getFile();

      //根据时间设置文件名
    Calendar calendar=Calendar.getInstance();
        String time=calendar.get(Calendar.YEAR)+""+calendar.get(Calendar.DAY_OF_YEAR)+""+calendar.getTimeInMillis();
        String fileName = time+file.getFileName();

    InputStream streamIn = null; //输入输出流
    OutputStream streamOut = null;
    String sysroot = servlet.getServletContext().getRealPath("/download/upload"); //获取图片文件夹路径    
    String filePath = sysroot + "//" + fName; //最终路径
    try {
     streamIn = file.getInputStream(); //以下是上传的代码,不用变,固定的
     streamOut = new FileOutputStream(filePath);
     int bytesRead = 0;
     byte[] buffer = new byte[20480];
     while ( (bytesRead = streamIn.read(buffer, 0, 20480)) != -1) {
     streamOut.write(buffer, 0, bytesRead);
     }
     streamOut.close();
     streamIn.close();
    request.setAttribute("info", "上传成功啦");
   
     }
     catch (FileNotFoundException e) {
     request.setAttribute("error", "上传失败啦");
     e.printStackTrace();
     return mapping.findForward("jumpErrorPage");
     }
     catch (IOException e) {

     request.setAttribute("error", "上传失败啦");
     e.printStackTrace();
     return mapping.findForward("jumpErrorPage");
     }

 

 return mapping.findForward("jumpSuccessPage");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值