이미지 업로드 및 파일 업로드는 본질적으로 동일하며 이미지 자체도 파일입니다. 파일 업로드는 서버에 이미지를 업로드하는 것입니다. 여러 가지 방법이 있지만 기본 구현은 파일 읽기 및 쓰기에 관한 것입니다.
주목해야 할 것
1. 양식은 속성 enctipe = "multipart/form-data"를 작성해야합니다.
2. 파일을 성공적으로 업로드 할 수 있도록 파일 컨트롤의 이름 속성 값은 제출 한 제어 계층 변수 이름과 일치해야합니다.
예를 들어, 공간 이름이 파일 인 경우 백그라운드에서 파일을 정의해야합니다.
개인 파일 파일; // 파일 제어 이름 개인 문자열 filecontentType; // 이미지 유형 개인 문자열 파일 필레나 이름; // 파일 이름
1.JSP 페이지
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 transitional // en" "http://www.w3.org/tr/tml/html 4/tml/html 4/tml 4.html/html 4.tml. <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"> <meta http-equiv = "pragma"content = "no-cache"/> <base target = "_ self"> <title> 파일 업로드 </head> <comper = "action =" "" ENCTYPE = "multipart/form-data"> <input type = "file"name "="file "value ="file "> <input type ="value = "식별"> </form> </body> </html>
1. 페이지 데이터에 제출 해야하는 컨트롤러
package com.cpsec.tang.chemical.action; import java.io.file; import java.io.ioexception; import java.util.random; import javax.annotation.resource; import javax.servlet.http.httpervletrequest; import org.apache.commons.fileutils; org.apache.struts2.servletactioncontext; import org.springframework.stereotyp.controller; import com.cpsec.tang.chemical.biz.lunbobiz; import com.cpsec.tang.chemical.entity.image; import com.opensymphony.xworkony2.actionsupport; @controller ") ActionSupport { / ** * * / 개인 정적 최종 최종 긴 SerialversionUid = 1L; @Resource (name = "lunbobiz") private lunbobiz lunbobiz; 개인 이미지 이미지; 개인 파일 파일; // 파일 제어 이름 개인 문자열 filecontentType; // 이미지 유형 개인 문자열 파일 필레나 이름; // 파일 이름 개인 정수 번호; public String findImage () {image = lunbobiz.findimage (); 반환 성공; } public String alterimage () {image = lunbobiz.findimage (); 반환 성공; } public String alterimage1 () {httpservletRequest request = servletActionContext.getRequest (); 문자열 root = request.getRealPath ( "/upload"); // 이미지가 업로드 될 서버 경로 [] = filefilename.split ( "//"); 문자열 filename = ""; if (names.length> = 1) {filename = getrandomstring (20)+"."+names [names.length-1]; } string picpath = "upload/"+filename; // 데이터베이스 파일에 저장된 이미지의 경로 1 = 새 파일 (루트); try {fileutils.copyfile (file, new File (file1, filename)); }} catch (ioexception e) {e.printstacktrace (); } 반환 성공; } /*임의의 문자열 가져 오기* /public string getRandomString (int length) {// 길이는 생성 된 문자열의 길이를 나타냅니다. string base = "abcdefghijklmnopqrstuvwxyz0123456789"; 랜덤 random = new random (); StringBuffer sb = new StringBuffer (); for (int i = 0; i <length; i ++) {int number = random.nextint (base.length ()); sb.append (base.charat (number)); } return sb.toString (); }}이것은 복사하여 파일을 업로드하는 것이며 다른 방법이 있습니다.
방법 2
@Controller ( "ContractAction") Public Class Contractaction은 ActionSupport를 확장합니다 {private final static string uploaddir = "/files"; // 파일을 업로드하는 경로, WebContent에서 개인 파일 파일을 만듭니다. // 입력 제어 이름은 파일이어야합니다. // filename collection private string filefilename; // 파일 업로드 콘텐츠 유형 모음 개인 문자열 FILECONTENTTYPE; 개인 문자열 파일 이름; public string upload ()는 filenotfoundexception, ioexception {string path = uploadfile (); // 파일 저장 데이터베이스 반환 성공; } // 업로드 함수를 실행합니다 @SuppressWarnings ( "Deprecation") public String uploadFile ()는 filenotFoundException, ioException {inputStream in = new FileInputStream (file); String dir = servletactionContext.getRequest (). getRealPath (uploadDir); 파일 filelocation = 새 파일 (dir); // 응용 프로그램 루트 디렉토리에서 대상 업로드 디렉토리를 수동으로 생성 할 수도 있습니다. if (! iscreated) {// 생성 된 대상 업로드 디렉토리를 생성하지 못하면 사용자 정의 예외를 던지는 것과 같은 다른 처리가 수행 될 수 있습니다.이 상황은 일반적으로 발생해서는 안됩니다. 널 리턴; }} // this.setFileFileName (getRandomString (20)); 문자열 [] name = this.getFileFileName (). split ( "//."); 문자열 filename = getRandomString (20)+"."+이름 [name.length-1]; this.setFileFileName (filename); System.out.println (filename); file uploadfile = 새 파일 (dir, filename); outputStream out = 새 FileOutputStream (uploadFile); 바이트 [] 버퍼 = 새로운 바이트 [1024 * 1024]; int 길이; while ((길 } in.close (); out.close (); uploaddir.substring (1)+"//"+filefilename; } catch (filenotfoundException ex) {return null; } catch (ioException ex) {return null; }} public static string getRandomString (int length) {String str = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789"; 랜덤 random = new random (); StringBuffer sb = new StringBuffer (); for (int i = 0; i <길이; i ++) {int number = random.nextint (62); sb.append (str.charat (number)); } return sb.toString (); }} 단일 이미지 업로드 외에도 여러 이미지 업로드가 있으며 원칙은 동일합니다.
패키지 com.cpsec.tang.chemical.action; import java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputstream; import java.io.outputStream; import java.util.List;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;/** * Multi-file upload*/public class FilesUploadAction extends ActionSupport { //Upload file storage path private final static String UPLOADDIR = "/업로드"; // 파일 컬렉션을 업로드 개인 목록 <file> 파일; // 파일 이름을 업로드 개인 목록 <string> filefilename; // 파일 업로드 콘텐츠 유형 모음 개인 목록 <string> filecontentType; 공개 목록 <file> getFile () {return 파일; } public void setfile (list <file> 파일) {this.file = file; } public list <string> getFileFileName () {return fileFilename; } public void setFileFileName (list <string> filefilename) {this.fileFilename = FileFilename; } public list <string> getFileContentType () {return fileContentType; } public void setFileContentType (list <string> fileContentType) {this.FileContentType = filecontentType; } public string uploadform ()은 예외를 {httpservletrequest 요청 = servletactionContext.getRequest (); String webpath = null; // 업로드 경로 (int i = 0; i <file.size (); i ++) {// 각 파일 업로드 업로드 (i); webpath = "upload/"+this.getFileFileName (). get (i); } 반환 "성공"; } // 업로드 함수 실행 개인 문자열 업로드 파일 (int i)은 filenotfoundException, ioException {try {inputStream in = new FileInputStream (file.get (i)); String dir = servletactionContext.getRequest (). getRealPath (uploadDir); 파일 filelocation = 새 파일 (dir); // 여기에서는 응용 프로그램 루트 디렉토리에서 대상 업로드 디렉토리를 수동으로 만들 수 있습니다. if (! filelocation.exists ()) {boolean iscreated = filelocation.mkdir (); if (! iscreated) {// 대상 업로드 디렉토리가 만들어지면 사용자 정의 예외를 던지는 것과 같은 다른 처리를 수행 할 수 있습니다.이 상황은 발생하지 않아야합니다. 널 리턴; }} string filename = this.getFileFileName (). get (i); file uploadfile = 새 파일 (dir, filename); outputStream out = 새 FileOutputStream (uploadFile); 바이트 [] 버퍼 = 새로운 바이트 [1024 * 1024]; int 길이; while ((길 } in.close (); out.close (); retury uploadfile.toString (); } catch (filenotfoundException ex) {return null; } catch (ioException ex) {return null; }}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.