struts上傳圖片的類

調用的地方

<a onClick="javascript:window.open('jsp/uploadphoto.jsp','myfacewindow', 'height=100,width=440, top=350, left=400, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');" style="cursor:hand;"><span class="STYLE2">上傳</span></a> 推薦最佳比例爲:(50px*50px)


下面是上傳的界面    uploadphoto.jsp

<%@page contentType="text/html; charset=GBK" import="java.util.HashMap"%>
<style type="text/css">
<!--
body {
 margin-left: 0px;
 margin-top: 0px;
 margin-right: 0px;
 margin-bottom: 0px;
}
.STYLE1 {
 font-size: 12px;
 color: #000000;
}
.STYLE2 {
 color: #006699;
 font-weight: bold;
}
-->
</style>
<html>
<title>上傳圖片</title>
<body>&nbsp;<br/>
&nbsp;<span class="STYLE2">商務客圖片上傳</span><br/>
&nbsp;<span class="STYLE1">請您選擇您要上傳的圖片,圖片推薦:50像素*50像素!使用.jpg .gif .bmp格式</span>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <form id="uploadphoto_f" name="uploadphoto_f" enctype="multipart/form-data" method="post" action="../uploadphoto.do">
  <tr>
    <td height="41">
 <input name="flag" type="hidden" value="myface" />
 <input name="loadpathto" type="hidden" value="/uploadcard/myface/" />
 &nbsp;<input name="uploadphoto" type="file" id="uploadphoto" size="40" />
  <input name="upload_b" type="submit" id="upload_b" value=" 上傳 " /></td>
  </tr></form>
</table>
</body>
</html>
<%String msg=request.getAttribute("msg")==null?"":request.getAttribute("msg")+"";
  if(!msg.equals("")){
%>
<script>
opener.document.location.href="Userinfo.do";
window.close();
</script>
 
<%}%>

接着是FORM 類       uploadphotoForm

package com.onlysoft.txl.user;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: fishsoft</p>
 *
 * @author Danny
 * @version 1.0
 */
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;

public class uploadphotoForm extends ActionForm {
 protected FormFile uploadphoto;
 public FormFile getUploadphoto() {
     return uploadphoto;
 }

 public void setUploadphoto(FormFile theFile) {
     this.uploadphoto = theFile;
 }
 
 public ActionErrors validate(
     ActionMapping mapping,
     HttpServletRequest request) {
   ActionErrors errors = null;
   //has the maximum length been exceeded?
   Boolean maxLengthExceeded =
       (Boolean) request.getAttribute(
           MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);

   if ( (maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
     errors = new ActionErrors();
     errors.add(
         ActionMessages.GLOBAL_MESSAGE,
         new ActionMessage("maxLengthExceeded"));
   }
   return errors;
 }
 
 

}

這個是action類     uploadphotoAction

  1package com.onlysoft.txl.user;
  2
  3/**
  4 * <p>Title: </p>
  5 *
  6 * <p>Description: </p>
  7 *
  8 * <p>Copyright: Copyright (c) 2006</p>
  9 *
 10 * <p>Company: fishsoft</p>
 11 *
 12 * @author Danny
 13 * @version 1.0
 14 */

 15import javax.servlet.http.HttpServletRequest;
 16import javax.servlet.http.HttpServletResponse;
 17import org.apache.struts.action.ActionForm;
 18import org.apache.struts.action.ActionMapping;
 19import org.apache.struts.action.ActionForward;
 20
 21import com.onlysoft.txl.*;
 22import java.sql.ResultSet;
 23import java.util.Map;
 24import java.util.HashMap;
 25import java.util.ArrayList;
 26import java.util.List;
 27import com.onlysoft.txl.mail.client.SenderMail;
 28import org.apache.struts.Globals;
 29import org.apache.struts.action.ActionMessage;
 30import org.apache.struts.action.ActionMessages;
 31import org.apache.struts.upload.FormFile;
 32import java.io.InputStream;
 33import java.io.ByteArrayOutputStream;
 34import javax.servlet.http.HttpSession;
 35import java.io.FileOutputStream;
 36import java.io.OutputStream;
 37
 38public class uploadphotoAction extends BaseAction{
 39  public ActionForward execute(
 40        ActionMapping mapping,
 41        ActionForm form,
 42        HttpServletRequest request,
 43        HttpServletResponse response) throws Exception {
 44   init(request);
 45   if (!isLogin) {
 46        return mapping.findForward("relogin");
 47        }

 48   String flag = request.getParameter("flag");
 49   String loadpathto = request.getParameter("loadpathto");
 50   String filePath = request.getRealPath("/"); //取當前系統路徑
 51   String pathphoto = loadpathto;
 52
 53
 54   if (form instanceof uploadphotoForm) {//如果form是uploadsForm
 55     String encoding = request.getCharacterEncoding();
 56     if ((encoding != null&& (encoding.equalsIgnoreCase("utf-8")))
 57        {
 58            response.setContentType("text/html; charset=GBK");//如果沒有指定編碼,編碼格式爲GBk
 59        }

 60    uploadphotoForm theForm = (uploadphotoForm ) form;
 61    FormFile file = theForm.getUploadphoto();//取得上傳的文件
 62    try {
 63      InputStream stream = file.getInputStream(); //把文件讀入
 64
 65      ByteArrayOutputStream baos = new ByteArrayOutputStream();
 66
 67      if (file.getFileSize() > (200 * 1024)) {
 68        request.setAttribute("message""文件請控制在200K以下!");
 69        return mapping.findForward("ErrorInfo");
 70      }

 71      String contentType = file.getContentType();
 72      System.out.println("文件類別:=" + contentType);
 73      String filebackstr = "";
 74      if (contentType.equals("image/pjpeg")) {
 75        filebackstr = ".jpg";
 76      }
 else if (contentType.equals("image/gif")) {
 77        filebackstr = ".gif";
 78      }
 else if (contentType.equals("image/bmp")) {
 79        filebackstr = ".bmp";
 80      }
 else {
 81        request.setAttribute("message""文件格式不正確!");
 82        return mapping.findForward("ErrorInfo");
 83      }

 84      OutputStream bos = new FileOutputStream(filePath + pathphoto +
 85                                              userid + file.getFileName()); //建立一個上傳文件的輸出流
 86      int bytesRead = 0;
 87      byte[] buffer = new byte[8192];
 88      while ( (bytesRead = stream.read(buffer, 08192)) != -1{
 89        bos.write(buffer, 0, bytesRead); //將文件寫入服務器
 90      }

 91      bos.close();
 92      stream.close();
 93    }

 94    catch(Exception e){
 95     System.err.print(e);
 96    }

 97     String sql="update sync4j_user set MYFACEPATH='" +pathphoto.replaceFirst("/",""+userid+file.getFileName()+"' where userid="+userid;
 98    db.doSql(sql, db.DELETE_MODE, conn);
 99
100   }
else{
101        request.setAttribute("message""上傳有誤");
102        return mapping.findForward("ErrorInfo");
103   }

104
105
106
107   request.setAttribute("msg""上傳成功");
108   return mapping.findForward("loadok");
109
110  }

111}

發佈了2 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章