Java上传文件(简单例子)

jsp页面:
  <%-- 有附件的话:要设置enctype属性;  --%>
  <html:form action="submitPublishReply.do" method="POST" onsubmit="return check();"  enctype="multipart/form-data">
  附件:<input type="file" name="attach" />
  <input type="submit" value="回 复" />
  </ul>
  </html:form>
  ActionForm:
  private FormFile file;
  Action:
  import org.apache.commons.fileupload.*;
  import org.apache.commons.fileupload.disk.*;
  import org.apache.commons.fileupload.servlet.*;
  import java.io.PrintWriter;
  import java.io.File;
  import org.apache.struts.upload.FormFile;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.io.FileOutputStream;
  //附件
  FormFile file = (FormFile) replyForm.getFile();
  if (file != null && file.getFileName().trim().length() > 0) {
  String fileName = file.getFileName();
  byte[] b = file.getFileData();
  String dir = request.getRealPath("/uploadfile"); //request.getRealPath获得web应用程序在服务器的绝对路径
  OutputStream streamOut = new FileOutputStream(dir + "/" +
  fileName);
  streamOut.write(b, 0, b.length);
  }

你可能感兴趣的:(Java上传文件(简单例子))