日期:2014-05-20  浏览次数:20678 次

求上传附件和上传图片的代码(我在网上找了一些,都用不了)
我在做一个上传文件和图片的程序,使用的是ssh。
需求:上传文件要支持大部分文件类型。
  上传图片要求可以上传所有图片类型和flash。如果jspsmart*这个能上满足要求,最好用这个组件。

之前我在网上找了一些代码,由于我水平有限,怎么改都不能正常上传。

谢谢!

------解决方案--------------------
给你段我刚刚写的代码吗, struts2里面上传的组件封装的方法也是这个么写的
[code=JAVA]
HttpServletRequest request = ServletActionContext.getRequest();
MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;

String path = ServletActionContext.getServletContext().getRealPath("/");

String filepath = path + "temp/";

    Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
    while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
      // get the value of this input tag
      String inputName = (String) fileParameterNames.nextElement();

      // get the content type
      String[] contentType = multiWrapper.getContentTypes(inputName);

      if (isNonEmpty(contentType)) {
        // get the name of the file from the input tag
        String[] fileName = multiWrapper.getFileNames(inputName);

        if (isNonEmpty(fileName)) {
        filepath += fileName[0];
          // get a File object for the uploaded File
          File[] files = multiWrapper.getFiles(inputName);
         
         
          try {
          BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[0]));//获得文件输入流
          FileOutputStream a = new FileOutputStream(new File(filepath));
            BufferedOutputStream output = new BufferedOutputStream(a);
           
            byte[] buff = new byte[2048];
            int bytesRead;

            while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {
            output.write(buff, 0, bytesRead);
            }
           
            output.flush();
            output.close();
            in.close();
} catch (Exception e) {
e.printStackTrace();
}
        }
      }
    }
[/code]

文件上传无非就是获得上传的文件对象转换为流,再写入服务器你指定的目录,仅些而已