이전 섹션에서는 제품 추가 및 업데이트 기능을 완료했습니다. 이 두 부분에는 제품 사진 업로드가 포함되며 자세한 설명은 없습니다. 이를 위해이 기사는 파일 업로드를 구현하기위한 struts2의 기능을 소개합니다.
1. 파일 정보를 캡슐화합니다
먼저 파일 정보를 캡슐화하려면 모델이 있어야합니다. 이 모델에는 파일, 파일 유형 및 파일 이름의 세 가지 속성이 필요합니다. 통과하려는 사진의 경우 다음과 같이 새 모델을 만듭니다.
public class fileImage {개인 파일 파일; 개인 문자열 contentType; 개인 문자열 파일 이름; 공개 파일 getFile () {return file; } public String getContentType () {return contentType; } public String getFileName () {return filename; } public void setUpload (파일 파일) {// 세트 메소드는 속성 이름과 동일 할 수 없지만 전경에서 전달 된 경우 매개 변수는 설정 메소드 이름과 동일해야합니다. 즉, 전경에 전달 된 매개 변수는 fileImage.upload this.file = file입니다. } public void setUploadContentType (String ContentType) {this.contentType = contentType; } public void setuploadfilename (String filename) {this.filename = filename; }}이런 식으로 모델이 작성됩니다. 파일 업로드의 논리가 단일 작업에 고유하지 않다는 점을 고려하면 파일 업로드의 논리를 도구 클래스에 작성하여 모든 작업 호출을 작성할 수 있습니다. 따라서 새로운 파일 업로드 도구 클래스를 만듭니다 (인터페이스 프로그래밍을 위해 도구 클래스 인터페이스도 추출).
2. 파일 업로드 도구 클래스를 완료하십시오
// 파일 업로드 도구 클래스 인터페이스 공용 인터페이스 파일 upload {// 파일 업로드의 함수 구현, 공개 초록 문자열 업로드 파일 (fileImage fileImage)을 업로드 한 후 새 파일 이름을 반환합니다. } // 파일 업로드 도구 클래스 특정 구현 @component ( "FileUpload") public class fileUploadUtil impless fileUpload {private String filepath; @Value ( "#{prop.filepath}") // value는 beans.xml 파일에서 id = "prop"로 bean을 찾는 것을 의미합니다. 주석을 통해 속성 구성 파일을 읽은 다음 해당 구성 파일에서 key = filepath의 값을 읽습니다. public void setfilepath (String Filepath) {System.out.println (filepath); this.filepath = filepath; } // 1. 확장자 개인 문자열 getFileExt (String filename) {return filenameutils.getextension (filename); } // 2. 새 파일 이름 개인 문자열 NewFilename (String filename) {String ext = getFileExt (filename)로 임의의 UUID 번호를 생성합니다. uuid.randomuuid (). toString () + "를 반환합니다." + 내선; } // 파일 업로드 함수를 구현하고 @override public string uploadfile (fileImage fileImage) {// 새 고유 파일 이름 문자열 pic = newFilename (fileImage.getFilename ())을 가져 오는 후 새 파일 이름을 반환합니다. try {fileUtil.copyFile (fileImage.getFile (), 새 파일 (filepath, pic)); // 첫 번째 매개 변수는 업로드 된 파일이고 두 번째 매개 변수는 파일을 새 경로 반환 그림에 복사하는 것입니다. } catch (예외 e) {throw new runtimeexception (e); } 마침내 {fileImage.getFile (). delete (); }}}위의 @Value 주석이 있는데, 이는 파일이 속성 파일에서 저장 될 경로를 얻는 것입니다. 자세한 내용은 구성 파일 정보를 얻으려면 Spring을 참조하십시오.
3. 캡슐화 된 파일 클래스 및 도구 클래스를 작동
파일 캡슐화 클래스와 파일 업로드 툴 클래스를 작성한 후이 두 객체를 동작에 주입하여 파일 업로드 함수를 동작에서 구현할 수 있도록해야합니다.
@Controller ( "BaseAction") @Scope ( "프로토 타입") 공개 클래스 BASEECIP <T> ACTOCTUPPORT AMPSERMENTS RequestAware, SessionAware, ApplicationAware, ModelDriven <T> {// Protected FileImage FileImage; // 파일 도구 클래스 업로드 @Resource Protected FileUpload FileUpload; public fileImage getFileImage () {return fileImage; } public void setFileImage (fileImage fileImage) {this.fileImage = fileImage; } // 다른 관련없는 코드를 생략 ...} 4. 파일 업로드를 구현하십시오
좋아, 이제 우리는 Productaction에서 파일 업로드를 구현할 수 있습니다. 도구 클래스가 작성되면 동작의 코드 금액이 매우 작으며 이는 캡슐화에 의해 제기 된 이점도 있습니다.
@Controller ( "ProductAction") @Scope ( "프로토 타입") Public Class ProductAction은 BaseAction <Product> {// 다른 관련없는 코드를 생략합니다 ... Public void save () 예외 {// fileUpload 도구 클래스가 추출되며, uploadFile 메소드는 파일 이름을 직접 수용하고 새 이미지 pic = fileUpliMate (fileImage); model.setpic (pic); model.setDate (새 날짜 ()); System.out.println (모델); // 제품 정보는 ProductService.Save (Model)에 저장됩니다. } public void update () {문자열 pic = fileUpload.uploadfile (fileImage); model.setpic (pic); model.setDate (새 날짜 ()); System.out.println (모델); // ProductService.update (모델) 업데이트; }}이런 식으로, 우리는 프론트 데스크에서 파일을 업로드하는 기능을 완료합니다.
원본 주소 : http://blog.csdn.net/eson_15/article/details/51366384
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.