当前页面: 开发资料首页 → J2EE 专题 → 100分求一代码(照片的上传)
100分求一代码(照片的上传)
摘要: 100分求一代码(照片的上传)
本人在炼习照片的上传,但不知道怎么做,要求是这样的:照片单独存一个文件,路径存在数据库里面..
请哪位好心人,给小弟一段代码,调式成功立即给分,不胜感激~
<%@ taglib uri="http://myfaces.sourceforge.net/tld/myfaces_ext_0_9.tld" prefix="x"%>
<table height="100" cellpadding="0" cellspacing="0">
<tr height="30">
<td colspan="2">アップロードのファイルを指定して下さい
</td>
</tr>
<tr height="20">
<td id="hello" width="100"> </td>
<td >
value="#{UploadFileForm.compositionUpFile}" style="height:30px;border:1px solid;background:white;font:bold 12px;height:18px;width:250px" styleClass="input_large" required="false"/>
</td>
</tr>
<tr height="50">
<td colspan="2">
</td>
</tr>
</table>
上边是页面代码,
下边是处理代码:
package jp.co.isec.jh.publish.bean;
import java.sql.Connection;
import java.sql.SQLException;
import javax.faces.context.FacesContext;
import jp.co.isec.jh.common.app.FileManage;
import jp.co.isec.jh.common.bean.MessageFactory;
import jp.co.isec.jh.common.bean.SystemInfo;
import jp.co.isec.jh.common.bean.UserBean;
import jp.co.isec.jh.common.database.ConnectionControl;
import jp.co.isec.jh.common.util.DateFormat;
import jp.co.isec.jh.dao.DaoVReleaseHistory;
import jp.co.isec.jh.dao.VoRelease;
import jp.co.isec.jh.publish.app.ReleasePublishApp;
/**
* ファイルアップロードActionBean
*/
public class UploadFileAction {
/** フェースコンテキスト */
private FacesContext facesContext = null;
/** メッセージ表示クラス */
private MessageFactory messageFactory = null;
/** ファイルアップロードFormBean */
private UploadFileForm formBean = null;
/** システム情報 Bean */
private SystemInfo systemInfo = null;
/** ユーザBean */
private UserBean userBean = null;
/**
* UploadFileActionの初期処理。
*/
public UploadFileAction() {
facesContext = FacesContext.getCurrentInstance();
messageFactory = new MessageFactory();
//ファイルアップロードFormBeanを取得する
formBean = (UploadFileForm)facesContext
.getApplication()
.getVariableResolver()
.resolveVariable(facesContext,"UploadFileForm");
//システム情報 Beanを取得する
systemInfo = (SystemInfo)facesContext
.getApplication()
.getVariableResolver()
.resolveVariable(facesContext,"SystemInfo");
//ユーザBeanを取得する
userBean = (UserBean)facesContext
.getApplication()
.getVariableResolver()
.resolveVariable(facesContext,"UserBean");
}
/**
* 登録ボタンの処理。
* @return ページの移転
*/
public String publish() {
ReleasePublishApp app = new ReleasePublishApp(); //リリース発行 App
FileManage fileManage = new FileManage(); //アップロードファイルをマスター
VoRelease vo = new VoRelease(); //リリースvo
String separator = "";
String fileName = ""; //ファイル名
String realPath = "";
String publishDate = DateFormat.nowTime(DateFormat.DATE_FORMAT); //発行日付
String url = "";
Connection con = null;
//版数の取得
String version = (String) facesContext.getExternalContext()
.getRequestParameterMap()
.get("version");
//モジュールIDの取得
String moduleId = (String) facesContext.getExternalContext()
.getRequestParameterMap()
.get("moduleId");
//リリース種別の取得
String fileType = (String) facesContext.getExternalContext()
.getRequestParameterMap()
.get("fileType");
//リリースFTPアドネスの取得
String ftp = (String) facesContext.getExternalContext()
.getRequestParameterMap()
.get("ftp");
//装置IDの取得
String deviecId = (String) facesContext.getExternalContext()
.getRequestParameterMap()
.get("deviecId");
try {
//モジュールをチェック
if(moduleId.trim().equals("")) {
messageFactory.ShowMessage("PUBLISH_MODULE_NOTEXIST");
return "";
}
//ファイルを入力チェック
if(formBean.getCompositionUpFile() == null) {
messageFactory.ShowMessage("PUBLISH_FILE_NOTINPUT");
return "";
}
//ファイルが存在したかどうかのチェック
if( formBean.getCompositionUpFile().getBytes().length == 0 ) {
if( fileType.trim().equals("sd") ){
messageFactory.ShowMessage("PUBLISH_SD_NOTEXIST"); //SDファイル
}else if( fileType.trim().equals("notification") ){
messageFactory.ShowMessage("PUBLISH_NOTIFICATION_NOTEXIST"); //通知書
}else if( fileType.trim().equals("composition") ){
messageFactory.ShowMessage("PUBLISH_COMPOSITION_NOTEXIST");//ファイル構成図
}
return "";
}
//ファイルをアップロード
//システムファイルのセパレータを取得する
separator = System.getProperty("file.separator");
realPath = systemInfo.getContextPath() + "Upload" + separator + "Publish"//発行
+ separator + "Release"//リリース
+ separator + moduleId //モジュールID
+ separator + publishDate.replaceAll("/", "") //発行日付
+ separator + version //版数
+ separator;
//Url
separator = "/";
url = "Upload" + separator + "Publish" //発行
+ separator + "Release" //リリース
+ separator + moduleId //モジュールID
+ separator + publishDate.replaceAll("/", "") //発行日付
+ separator + version //版数
+ separator;
fileName = fileManage.getFileName(formBean.getCompositionUpFile().getName());
fileManage.writeFile(realPath, fileName, formBean.getCompositionUpFile().getBytes());
formBean.setComposition(url + fileName);
try {
//接続を取得する
con = new ConnectionControl().getConnection();
DaoVReleaseHistory dao = new DaoVReleaseHistory( con );
float release = dao.getReleaseId( Integer.parseInt( moduleId ) ,Float.parseFloat( version ) );
vo.setReleaseID( (int)release ); //リリースID
vo.setUserID(userBean.getUserID());//発行者
vo.setReleaseDate( publishDate ); //発行日付
vo.setDeviceID(Integer.parseInt( deviecId )); //装置ID
vo.setModuleID(Integer.parseInt( moduleId )); //モジュール
vo.setVersion(Float.parseFloat( version )); //版数
if( fileType.trim().equals("sd") ){
vo.setDescFilename(formBean.getComposition()); //SDファイル
}else if( fileType.trim().equals("notification") ){
vo.setNotification(formBean.getComposition());//通知書
}else if( fileType.trim().equals("composition") ){
vo.setFileComposition(formBean.getComposition());//ファイル構成図
}
vo.setFTPAddress( ftp ); //FTPアドレス
//リリーステーブルを更新する
app.update(con, vo);
con.commit();
} catch(SQLException e) {
//リリーステーブルを更新する時エラー発生の場合に関する処理
try {
con.rollback();
} catch (Exception c) {
}
messageFactory.ShowMessage("PUBLISH_DB_ERROR");
} finally {
//コネクションのクローズ
try {
if(con != null) {
con.close();
}
} catch (Exception e) {
}
}
} catch (Exception e) {
return "";
}
messageFactory.ShowMessage("RELEASE_UPLOAD_SUCCESS");
//クローズフラグ
formBean.setCloseFlag("1");
return "updateFile";
}
}
需要用到上传组件(UploadedFile ):
FORMBEAN代码:
/*
* タイトル: JHシステム
* 会社名: ISEC
* 著作権: Copyright (c) 2005
* Created on 2006/05/25
* @version 1.0
* @author ZuoChuanMin
*/
package jp.co.isec.jh.publish.bean;
import net.sourceforge.myfaces.custom.fileupload.UploadedFile;
/**
* ファイルアップロードFormBean
*/
public class UploadFileForm{
/** モジュールID */
private String moduleId = "";
/** 版数 */
private String version = "";
/** 発行日付 */
private String publishDate = "";
/** sd */
private String sd = "";
/** sdアップロード */
private UploadedFile sdUpFile;
/** 通知書 */
private String notification = "";
/** 通知書アップロード */
private UploadedFile notificationUpFile;
/** ファイル構成図 */
private String composition = "";
/** クローズフラグ */
private String closeFlag = "0";
/** ファイル構成図アップロード */
private UploadedFile compositionUpFile;
/**
* 発行日付を返す。
* @return 発行日付
*/
public String getPublishDate() {
return publishDate;
}
/**
* 発行日付を設定する。
* @param publishDate 発行日付
*/
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
/**
* モジュールIDを返す。
* @return モジュールID
*/
public String getModuleId() {
return moduleId;
}
/**
* モジュールIDを設定する。
* @param module モジュールID
*/
public void setModuleId(String module) {
this.moduleId = module;
}
/**
* 版数を返す。
* @return 版数
*/
public String getVersion() {
return version;
}
/**
* 版数を設定する。
* @param version 版数
*/
public void setVersion(String version) {
this.version = version;
}
/**
* ファイル構成図を返す。
* @return ファイル構成図
*/
public String getComposition() {
return composition;
}
/**
* ファイル構成図を設定する。
* @param composition ファイル構成図
*/
public void setComposition(String composition) {
this.composition = composition;
}
/**
* ファイル構成図アップロードを返す。
* @return ファイル構成図アップロード
*/
public UploadedFile getCompositionUpFile() {
return compositionUpFile;
}
/**
* ファイル構成図アップロードを設定する。
* @param compositionUpFile ファイル構成図アップロード
*/
public void setCompositionUpFile(UploadedFile compositionUpFile) {
this.compositionUpFile = compositionUpFile;
}
/**
* 通知書を返す。
* @return 通知書
*/
public String getNotification() {
return notification;
}
/**
* 通知書を設定する。
* @param notification 通知書
*/
public void setNotification(String notification) {
this.notification = notification;
}
/**
* 通知書アップロードを返す。
* @return 通知書アップロード
*/
public UploadedFile getNotificationUpFile() {
return notificationUpFile;
}
/**
* 通知書アップロードを設定する。
* @param notificationUpFile 通知書アップロード
*/
public void setNotificationUpFile(UploadedFile notificationUpFile) {
this.notificationUpFile = notificationUpFile;
}
/**
* SDを返す。
* @return SD
*/
public String getSd() {
return sd;
}
/**
* SDを設定する。
* @param sd SD
*/
public void setSd(String sd) {
this.sd = sd;
}
/**
* sdアップロードを返す。
* @return sdアップロード
*/
public UploadedFile getSdUpFile() {
return sdUpFile;
}
/**
* sdアップロードを設定する。
* @param sdUpFile sdアップロード
*/
public void setSdUpFile(UploadedFile sdUpFile) {
this.sdUpFile = sdUpFile;
}
/**
* クローズフラグを返す。
* @return クローズフラグ
*/
public String getCloseFlag() {
return closeFlag;
}
/**
* クローズフラグを設定する。
* @param closeFlag クローズフラグ
*/
public void setCloseFlag(String closeFlag) {
this.closeFlag = closeFlag;
}
}
好的,我明天试一下,再给分,真是谢谢
为了完美性,(Ejb冠军)你能否帮我改一下注释,看不懂啊,谢谢
冠军大哥,千万要帮我一下啊
给你一个上传方法
public boolean upload( UploadInfoForm uif,String path ) throws FileNotFoundException, IOException {
boolean flag = false;
FormFile file = uif.getFile();
FileUtil fu = new FileUtil();
String fileName = file.getFileName();
String fileExt = fu.getFileExtName(fileName);
String fileCode = uif.getFileCode();
//如果未上传文件 则文件名为空
if ( fileExt.length() != 0 ){
fileName = fileCode + "."+fileExt;
InputStream streamIn = file.getInputStream();
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
file.destroy();
flag = true;
}
return flag;
}
其实最关键的是你要去下载一个jspsmartupload的jar包 这个包用来上传东西的。
有了这个包,你只需要调用它的方法,具体的例子网上都有。
包早就下下来了,只是不会用呢
接分
jspsmartupload.jar包已经有了 如何把表单的数据(包含 一张图片,一条文本记录)通过提交给Servlet处理(Servlet里面的代码如何???????);Servlet调用Bean文件操作Oracle数据库(Bean文件里面的代码如何书写),将提交的数据插入到Oracle数据库中!
上面的太复杂了 看不懂 也不能调试成功!! 急 !!!!!!!!!!!
晕,注释都看不懂啊
Struts里的action和form:
Action:
package org.tyler.test.action;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.tyler.test.Services.UploadImage;
import org.tyler.test.Services.uploadFiles;
import org.tyler.test.form.UploadTestForm;
public class UploadTestAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UploadTestForm uploadTestForm = (UploadTestForm) form;
String name=uploadTestForm.getName();
FormFile file = uploadTestForm.getTheFile();
try {
InitialContext ctx = new InitialContext();
UploadImage uib = (UploadImage) ctx.lookup("UploadImageBean/remote");
String upFileName=uib.addImage(name,file.getFileName());
String strPathSeparator=System.getProperty("file.separator");
String filePath = "D:/jboss4/server/default/deploy/uploadfiles.war/"; //this.getServlet().getServletContext().getRealPath("/");
InputStream stream = file.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + upFileName);
//D:/Tomcat5/webapps/coka/UploadFiles/DSC01508.JPG
/* System.out.println(filePath +
"UploadFiles//"+file.getFileName());
System.out.println(filePath);*/
request.setAttribute("fileName", filePath + strPathSeparator
+ 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);
}
return mapping.findForward("success");
}
}
Form:
package org.tyler.test.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
public class UploadTestForm extends ActionForm {
private static final long serialVersionUID = 1L;
private String name;
private FormFile theFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public FormFile getTheFile() {
return theFile;
}
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}
}
ejb3实体和服务:
服务:接口自己写吧
package org.tyler.test.Services;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Stateless
@Remote(UploadImage.class)
public class UploadImageBean implements UploadImage,java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@PersistenceContext
EntityManager em;
public String addImage(String name,String path) {
uploadFiles upfile = new uploadFiles();
upfile.setName(name);
upfile.setPath(path);
em.persist(upfile);
int i1=path.lastIndexOf(".");
int i2=path.length();
String strExtend=path.substring(i1, i2);
StringBuffer sb=new StringBuffer();
sb.append(Integer.toString(upfile.getId()));
sb.append(strExtend);
upfile.setPath(sb.toString());
em.persist(upfile);
return sb.toString();
}
public List getAllUploadFiles() {
Query query=em.createQuery("select u from uploadFiles u");
System.out.println("query size:" + query.getResultList().size());
return query.getResultList();
}
public uploadFiles getUploadFileById(int id) {
return (uploadFiles) em.find(uploadFiles.class, id);
}
public int Update(uploadFiles info) {
em.merge(info);
return -1;
}
}
实体:
package org.tyler.test.Services;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
public class uploadFiles implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String path;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
给你个连接,自己看吧
http://blog.csdn.net/zhl0369/archive/2006/07/04/874082.aspx
后面有例子的
楼上给的这个太好了!:)
非常感谢各位,我知道你们给的都很好,只是,我还没有去弄过struts,ejb呢,分明天下午之前一定给完,不过我很希望有那位高手能加下小弟的qq:280049885,很想再问他几个问题,希望你们不要介意,真是感谢万分~~~在此,我说声:谢谢,谢谢,谢谢谢谢你们~祝贺各位:假期愉快,家庭美满,发大财
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
aadadad