JSF之上传图片(也可以用来上传其他文件)

本文介绍了一种使用JavaScript和Java实现的图片上传方法,该方法通过文件流而非组件完成图片上传。此外,还实现了图片预览功能,并详细展示了如何验证图片格式及处理上传过程中的各种细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没用组件来上传,是用的流来上传的

 <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="x"%> 
<h:form  enctype="multipart/form-data">
图片:<x:inputFileUpload id="fileId" value="#{picBean.myfile}" storage="file" onchange="showPic()"/>
     <img id="picId" height="30 width="30" />   
     <script type="text/javascript">
         function showPic(){
            var file= document.getElementById('addForm:fileId');
            var pic=document.getElementById('picId');
            pic.src=file.value;
         }
        </script>


PicBean.java
// 上传图片和类型不能为空
  if (myfile != null) {
   String fileName = new File(myfile.getName()).getName();
   String test = myfile.getContentType();
   if (!test.startsWith("image/")) {
    wrongpictype = "图片格式不对";
    return "";
   }
   String path=UploaderHelper.uploadFileToDisk(myfile);
   this.picnews.setTurl(path);
  }


UploaderHelper.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.apache.myfaces.custom.fileupload.UploadedFile;
public class UploaderHelper {
 public final static String uploadPath="uploadFile";

public static String uploadFileToDisk(UploadedFile myFile)
 {
  try {
   long time = System.currentTimeMillis();
   InputStream in = myFile.getInputStream();
   FacesContext ctx = FacesContext.getCurrentInstance();
   HttpSession hs = (HttpSession) ctx.getExternalContext().getSession(true);
   String directory = hs.getServletContext().getRealPath("//")+uploadPath;
   File fileDir = new File(directory);
   if (!fileDir.exists()) {
    fileDir.mkdir();
   }
   String fileName=String.valueOf(Thread.currentThread().getContextClassLoader().hashCode())+"_"+time+myFile.getName().substring(myFile.getName().lastIndexOf("."));
   String file = hs.getServletContext().getRealPath("//") + uploadPath+"//"+ fileName;
   BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
   byte[] buffer = new byte[1024 * 2];
   int length;
   while ((length = in.read(buffer, 0, buffer.length)) > 0) {
    out.write(buffer, 0, length);
   }
   out.flush();
   out.close();
   return uploadPath+"/"+ fileName;
//   return "//" + uploadPath+"//"+ fileName;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 public String downLoadFile()
 {
  String blobId=FacesUtils.getRequestParameter("blobFileID");
  BlobFile blobVO=blobFileService.getBlobFile(Integer.parseInt(blobId));
  HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
  ServletContext servletContext=FacesUtils.getServletContext();
        InputStream s = new java.io.ByteArrayInputStream(blobVO.getFileContent());
        BufferedInputStream bis =  new BufferedInputStream(s);
        String realName=blobVO.getName();
        String extendName=null;
        try {
            String mimeType = null;
            int pos = realName.lastIndexOf(".");
            if (pos >= 0 && (pos + 1) < realName.length()) {
                extendName = realName.substring(pos + 1);
            }
            if (extendName != null)
                mimeType = servletContext.getMimeType(extendName);
            if (mimeType == null)
                mimeType = "APPLICATION/OCTET-STREAM";

            response.setContentType(mimeType);
            response.setHeader("Content-Disposition", "attachment; filename=/"" + URLEncoder.encode(realName, "UTF-8") + "/"");
            byte[] data = new byte[1024];
            OutputStream out = response.getOutputStream();
            int length=0;
            do {
                length = bis.read(data);
                if (length != -1) {
                    out.write(data, 0, length);
                }
            } while (length > 0);
            out.flush();
            out.close();
            data = null;
            //
            response.setStatus(HttpServletResponse.SC_OK);
            response.flushBuffer();
        } catch (IOException ex) {
            response.setContentType("text/html");
            response.setHeader("Content-Disposition", "");
        } finally {
            try {
                if (bis != null)
                    bis.close();
            } catch (IOException ex) {
            }
        }
        FacesContext.getCurrentInstance().responseComplete();
  return null;
 }
 
  public String downLoadFileFromDisk()
 {
//  String blobId=FacesUtils.getRequestParameter("blobFileID");
//  BlobFile blobVO=blobFileService.getBlobFile(Integer.parseInt(blobId));
  String filepath=FacesUtils.getRequestParameter("filepath");;
  String realName=FacesUtils.getRequestParameter("realName");;
  HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
  ServletContext servletContext=FacesUtils.getServletContext();
        InputStream s=null;
  try {
   s = new BufferedInputStream(new FileInputStream(filepath));
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
        BufferedInputStream bis =  new BufferedInputStream(s);
        String extendName=null;
        try {
            String mimeType = null;
            int pos = realName.lastIndexOf(".");
            if (pos >= 0 && (pos + 1) < realName.length()) {
                extendName = realName.substring(pos + 1);
            }
            if (extendName != null)
                mimeType = servletContext.getMimeType(extendName);
            if (mimeType == null)
                mimeType = "APPLICATION/OCTET-STREAM";

            response.setContentType(mimeType);
            response.setHeader("Content-Disposition", "attachment; filename=/"" + URLEncoder.encode(realName, "UTF-8") + "/"");
            byte[] data = new byte[1024];
            OutputStream out = response.getOutputStream();
            int length=0;
            do {
                length = bis.read(data);
                if (length != -1) {
                    out.write(data, 0, length);
                }
            } while (length > 0);
            out.flush();
            out.close();
            data = null;
            //
            response.setStatus(HttpServletResponse.SC_OK);
            response.flushBuffer();
        } catch (IOException ex) {
            response.setContentType("text/html");
            response.setHeader("Content-Disposition", "");
        } finally {
            try {
                if (bis != null)
                    bis.close();
            } catch (IOException ex) {
            }
        }
        FacesContext.getCurrentInstance().responseComplete();
  return null;
 }
}

依赖的文件: tomahawk-1.1.3.jar commons-fileupload-1.2.jar commons-io-1.3.1.jar Tomahawk.tld 把这个三个包放在/WEB_INF/lib目录下面。Jsf依赖的包也放在这个目录下面 Tomahawk.tld放在/WEB-INF目录下。Jsf标签也放在这个目录下面。 这个主要讲jsf上传文件,因此只罗列了上传文件用到的包和标签。 Web-xml文件如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <!-- Context Listener creates and sets the application handler --> <!-- Faces Servlet --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Faces Servlet Mapping --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <filter> <filter-name>ExtensionsFilter</filter-name> <filter-class> org.apache.myfaces.component.html.util.ExtensionsFilter </filter-class> <init-param> <param-name>uploadMaxFileSize</param-name> <param-value>10m</param-value> </init-param> <init-param> <param-name>uploadThresholdSize</param-name> <param-value>100k</param-value> </init-param> </filter> <filter-mapping> <filter-name>ExtensionsFilter</filter-name> <!—要和<servlet-mapping>中的<servlet-name>一致--> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> 上传文件的页面如下: <%@ include file="tags.jsp"%> <f:view> <h:form id="MyForm" enctype="multipart/form-data" > <h:messages globalOnly="true" styleClass="message"/> <h:panelGrid columns="3" border="0" cellspacing="5"> <h:outputLabel for="myFileId" value="File: "/> <x:inputFileUpload id="myFileId" value="#{myBean.myFile}" storage="file" required="true"/> <h:message for="myFileId"/> <h:outputLabel for="myParamId" value="Param: "/> <h:selectOneMenu id="myParamId" value="#{myBean.myParam}" required="true"> <f:selectItem itemLabel="" itemValue=""/> <f:selectItem itemLabel="MD5" itemValue="MD5"/> <f:selectItem itemLabel="SHA-1" itemValue="SHA-1"/> <f:selectItem itemLabel="SHA-256" itemValue="SHA-256"/> <f:selectItem itemLabel="SHA-384" itemValue="SHA-384"/> <f:selectItem itemLabel="SHA-512" itemValue="SHA-512"/> </h:selectOneMenu> <h:message for="myParamId"/> <h:outputText value=" "/> <h:commandButton value="Submit" action="#{myBean.processMyFile}"/> <h:outputText value=" "/> </h:panelGrid> </h:form> </f:view> 其中tags.jsp文件如下: <%@ page language="java" pageEncoding="GB18030"%> <%@ page contentType="text/html" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="x"%> Faces-config.xml文件如下: <faces-config> <managed-bean> <managed-bean-name>myBean</managed-bean-name> <managed-bean-class> fileupload.MyBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </faces-config> MyBean如下: package com.dhc; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.apache.myfaces.custom.fileupload.UploadedFile; public class oaMailMainForm { private UploadedFile myFile; public UploadedFile getMyFile() { return myFile; } public void setMyFile(UploadedFile myFile) { this.myFile = myFile; } public String uploadedfile() { System.out.println("Entry"); try { InputStream in = new BufferedInputStream(myFile.getInputStream()); try { byte[] buffer = new byte[64 * 1024]; FileOutputStream fileOutputStream = new FileOutputStream( "C:\\My Files\\tst.jpg");// 这里可以把上传文件写服务器目录,或者数据库中 while (in.read(buffer) > 0) { fileOutputStream.write(buffer); } } finally { in.close(); } System.out.println("End"); return "success"; } catch (Exception x) { System.out.print("Exception"); FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_FATAL, x.getClass().getName(), x .getMessage()); FacesContext.getCurrentInstance().addMessage(null, message); return null; } } } 参考文献:http://www.blogjava.net/cooky/archive/2007/10/02/150176.html http://blog.youkuaiyun.com/meteorlWJ/archive/2008/01/09/2032505.aspx http://tml808.javaeye.com/blog/166853
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值