File 클래스 를 이용 하여 파일 업로드
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();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Spring에서 DAO가 순환 호출될 때 데이터가 실시간으로 업데이트되지 않는 해결 방법문제를 설명하기 전에 몇 가지 전제 사항을 설명하십시오. Spring의 구성 파일에서 다음과 같은 방식으로 데이터베이스 트랜잭션을 구성했다고 가정하십시오. 현재 UserDao 및 Security Service가 있습...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.