File 클래스 를 이용 하여 파일 업로드

6430 단어 DAOjvmhtmljsp.net
첫 번 째 단계:
jsp 페이지 에서 파일 업 로드 를 담당 하 는 컨트롤 은 html:file 탭 을 사용 하고 html:form 에 enctype="multipart/form-data"를 추가 하 는 것 을 주의 하 십시오.  post
1、

2、

           두상:
          

두 번 째 단계:
대응 하 는 폼 form 에서 private FormFile image 속성 을 정의 합 니 다.물론 set 와 get 방법 을 자동 으로 생 성 합 니 다.
세 번 째 단계:
pojo 에서 업로드 컨트롤 과 대응 하 는 속성 을 설명 합 니 다.
네 번 째 단계:
해당 Action 의 방법 에 업 로드 된 코드 를 추가 합 니 다.
예 를 들 면:
UserForm userForm = (UserForm) form;
		UserDAO dao = new UserDAO();
		String message = null;
		String basePath = this.getServlet().getServletContext()
				.getRealPath("/");	
//       	
		try {
			dao.getSession().beginTransaction();
User temp = (User) dao.findByUserName(userForm.getUserName());
			if (temp == null) {
				User user = new User();
				userForm.fillToUserBean(user);
				if (userForm.getImage().getFileName().length() > 0) {
		//           ,        >0
String path = "/uploadImages/" + 
//   "/uploadImages/"     ?       WebRoot                    , :             uploadfile ,       WebRoot       uploadfile    ,          :"/uploadfile/"
dao.picturePath(userForm.getImage());
//            DAO     picturePath   ,                                 ,                    ,              。    Action           DAO      。
					String endstring = userForm.getImage().getFileName()
							.substring(
									userForm.getImage().getFileName()
											.lastIndexOf(".") + 1);
if ("jpg".equals(endstring) || "png".equals(endstring)
					|| "gif".equals(endstring)) {
						try {
dao.saveFile(userForm.getImage(), basePath, path);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						user.setHeaderImg(path);
					} else {
						user.setHeaderImg("");
					}
				}
				dao.save(user);
				dao.getSession().getTransaction().commit();
				return mapping.findForward("index");

다섯 번 째 단계
DAO 에서 저 희 는 saveFile 을 수정 하고 picturePath 방법 을 추가 해 야 합 니 다.구체 적 인 코드 는 다음 과 같 습 니 다.
saveFile
public void saveFile(FormFile formfile, String basePath, String path)
			throws IOException {
		FileOutputStream fos = null;
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			fos = new FileOutputStream(basePath + path);
			in = new BufferedInputStream(formfile.getInputStream());
			out = new BufferedOutputStream(fos);
			byte[] buf = new byte[8192];
			int readsize;
			while ((readsize = in.read(buf)) != -1) {
				out.write(buf, 0, readsize);
				out.flush();
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fos != null)
				try {
					fos.close();
				} catch (Exception err) {
					err.printStackTrace();
				}
			if (in != null)
				try {
					in.close();
				} catch (Exception err) {
					err.printStackTrace();
				}
			if (out != null)
				try {
					out.close();
				} catch (Exception err) {
					err.printStackTrace();
				}

		}
	}

picturePath
public String picturePath(FormFile formfile) {
		String filename = "";
		UUIDGenerator g = new UUIDGenerator();
// UUIDGenerator                    ,         。
		filename = formfile.getFileName();
		if (filename.length() > 0) {
			filename = filename.substring(filename.lastIndexOf("."));
		}
		filename = (String) g.generate() + filename;
		return filename;
	}

여섯 번 째 단계:
작성 도구 클래스:UUIDGenerator
import java.io.Serializable;
import java.net.InetAddress;

public class UUIDGenerator {

	 private static final int IP;
	 public static int IptoInt( byte[] bytes ) {
	  int result = 0;
	  for (int i=0; i<4; i++) {
	   result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
	  }
	  return result;
	 }
	 static {
	  int ipadd;
	  try {
	   ipadd = IptoInt( InetAddress.getLocalHost().getAddress() );
	  }
	  catch (Exception e) {
	   ipadd = 0;
	  }
	  IP = ipadd;
	 }
	 private static short counter = (short) 0;
	 private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 );

	 public UUIDGenerator() {
	 }
	 protected int getJVM() {
	  return JVM;
	 }
	 protected short getCount() {
	  synchronized(UUIDGenerator.class) {
	   if (counter<0) counter=0;
	   return counter++;
	  }
	 }
	 protected int getIP() {
	  return IP;
	 }
	 protected short getHiTime() {
	  return (short) ( System.currentTimeMillis() >>> 32 );
	 }
	 protected int getLoTime() {
	  return (int) System.currentTimeMillis();
	 }
	 
	 private final static String sep = "";

	 protected String format(int intval) {
	  String formatted = Integer.toHexString(intval);
	  StringBuffer buf = new StringBuffer("00000000");
	  buf.replace( 8-formatted.length(), 8, formatted );
	  return buf.toString();
	 }

	 protected String format(short shortval) {
	  String formatted = Integer.toHexString(shortval);
	  StringBuffer buf = new StringBuffer("0000");
	  buf.replace( 4-formatted.length(), 4, formatted );
	  return buf.toString();
	 }

	 public Serializable generate() {
	  return new StringBuffer(36)
	   .append( format( getIP() ) ).append(sep)
	   .append( format( getJVM() ) ).append(sep)
	   .append( format( getHiTime() ) ).append(sep)
	   .append( format( getLoTime() ) ).append(sep)
	   .append( format( getCount() ) )
	   .toString();
	 }

	}

좋은 웹페이지 즐겨찾기