struts2 文件上传

来源:互联网 发布:php模板消息接口 demo 编辑:程序博客网 时间:2024/05/20 17:26
public String upload(String attachment) {
  FileOutputStream fos = null;
  FileInputStream fis = null;
  try {
   String filename = bean.getAppendix();
   String attachmentFileName = filename.substring(
     filename.lastIndexOf("\\"), filename.lastIndexOf("."));
   String type = filename.substring(filename.lastIndexOf("."));
   String realpath = ServletActionContext.getServletContext()
     .getRealPath("/attachments") + attachmentFileName + type;
   fos = new FileOutputStream(realpath);
   fis = new FileInputStream(attachment);
   byte[] buffer = new byte[1024];
   int len = 0;
   while ((len = fis.read(buffer)) > 0) {
    fos.write(buffer, 0, len);
   }
   return realpath;
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  } finally {
   close(fos, fis);
  }
 }