如何从jsp中读取文件名并将其用作图像的src?

时间:2011-02-02 06:20:25

标签: html jsp

<%
    System.out.println("Content Type ="+request.getContentType());
String fileBasePath = "c:/temp"; //Base path where you wanto store the files...
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(100000000);

    List fileItems = fu.parseRequest(request);
    Iterator itr = fileItems.iterator();

try{
    while(itr.hasNext()) {
      FileItem fi = (FileItem)itr.next();

      if(!fi.isFormField()) {
            File fNew= new File(fileBasePath, new File(fi.getName()).getName());
        System.out.println(fNew.getAbsolutePath());
        fi.write(fNew);
      }
      else {
        System.out.println("Field ="+fi.getFieldName());
      }
    }
}
catch(Exception e)
{
    System.out.println(e);
}

%>

1 个答案:

答案 0 :(得分:1)

创建一个Servlet,将图像作为InputStream并将其写入响应的OutputStream,然后在<img src>中调用该servlet。

E.g。

<img src="imageservlet/name.gif" />

InputStream input = new FileInputStream(new File("c:/temp", request.getPathInfo()));
OutputStream output = response.getOutputStream();
// Write input to output.

可以找到一个基本示例here