struts中上传文件-FormFile应用

来源:互联网 发布:ubuntu搬瓦工搭建vps 编辑:程序博客网 时间:2024/05/21 22:33

String encoding = request.getCharacterEncoding();
  if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
  {
   response.setContentType("text/html; charset=utf-8");//如果没有指定编码,编码格式为utf-8}
   UploadsActionForm theForm = (UploadsActionForm ) form;
   FormFile file = theForm.getFiles();//取得上传的文件
   try {
    InputStream stream = file.getInputStream();//把文件读入
    String filePath = request.getRealPath("/file");//上传到指定的file包中
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStream bos = new FileOutputStream(filePath + "/" + file.getFileName());//建立一个上传文件的输出流//
    System.out.println(filePath+"/"+file.getFileName());
    int bytesRead = 0;byte[] buffer = new byte[8192];
    while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1)
    {
     bos.write(buffer, 0, bytesRead);//将文件写入服务器
    }
    bos.close();
    stream.close();
   }catch(Exception e)
   {
    System.err.print(e);
   }

原创粉丝点击