Java 파일 업로드 및 파일 다운로드는 프로그램 개발에서 비교적 일반적인 기능입니다. 다음 기사는 Java에서 파일 업로드 및 다운로드를 구현하기위한 세 가지 솔루션을 소개합니다. 특정 세부 사항은 다음과 같습니다.
첫 번째 요점 : Java 코드는 파일 업로드를 구현합니다
formfile 파일 = manform.getFile (); String newFilename = null; string newPathName = null; String fileaddre = "/numup"; try {inputStream 스트림 = file.getInputStream (); // string filepath = request.getRealPath (fileaddre)로 파일을 읽습니다. file1) .mkdir (); newFilename = System.CurrentTimeMillis ()+ file.getFilename (). substring (file.getFilename (). lastIndexOf ( '.')); byTearRayoutPutStream baos = new ByTearRayoutputStream (); outputStream bos = new FileOutputStream (Fillepath+ "/"+ newFilename); newPathName = FilePath+"/"+NewFilename; System.out.println (newPathName); // 파일을 업로드하기위한 출력 스트림 생성 system.out.println (filepath+"/"+file.getfilename ()); int bytesread = 0; byte [] buflte [8192]; while ((bytesread = stream.read (buffer, 0, 8192))! = -1) {bos.write (buffer, 0, bytesread); // 파일을 서버에 쓰기} bos.close (); stream.close ();} catch (e.printstacktrace ()} catch (ioexmence e). {e.printstacktrace ();}두 번째 요점 : JSP 페이지에서 파일 업로드 구현
package com.vogoal.util; import java.io.bufferedoutputStream; import java.io.file; import java.io.fileoutputStream; import java.io.ioexception; import java.text.simpledateformat; import java.util.arraylist; import java.util.date; java.util; javax.servlet.servletinputStream; import javax.servlet.servlet.http.httpservletrequest; public class jspfileUpload {/** 요청 객체*/private httpservletrequest 요청 = null;/** 파일을 업로드하는 경로*/개인 문자열 업로드 = null;/** 크기의 크기를 얻는다. 1024*8;/** 매개 변수를 저장하는 Hashtable*/private hashtable paramht = new hasptable ();/** arraylist 업로드 된 파일의 파일 이름을 저장하는 arraylist*/private arraylist updfilearr = new arraylist ();/*** 요청 개체를 설정하십시오. ** @param request* httpservletrequest 요청 객체*/public void setRequest (httpservletrequest request) {this.request = request;}/* 파일 업로드 경로를 설정합니다. * * @param path * 사용자가 지정한 파일의 업로드 경로. */public void setuploadpath (문자열 경로) {this.uploadpath = path;}/*** 파일 업로드 처리를위한 기본 프로그램입니다. ������B * * @return int 작동 결과 0 파일 작동이 성공적이었습니다. 1 요청 객체가 존재하지 않습니다. 2 파일 저장 경로가 설정되지 않았거나 파일 저장 경로가 올바르지 않습니다. 3* 올바른 ENCTYPE가 설정되지 않았습니다. 4 파일 작동은 비정상적입니다. */public int process () {int status = 0; // 파일을 업로드하기 전에 요청 객체, 업로드 경로 및 ENCTYPE를 확인하십시오. 상태 = preCheck (); // 오류가 발생하면 오류 코드를 반환합니다. if (status! = 0) return status; try {// �� �� 매개 변수 또는 파일 이름 �U.String name = null; // valuestring value = null; // 파일 비트 부울 파일 플래그 = false; // 저장 될 파일인지 여부. 파일 tmpfile = null; // 업로드 된 파일 이름의 이름 fname = null; fileoutputStream baos = null; bufferedOutputStream bos = null; // �� ���hashTableParamht = new Hashtable (); updfilearr = new arraylist (); int rtnpos = 0; buffs = buff =/// � contentTypestring contentType = request.getContentType (); int index = contentType.IndexOf ( "boundary ="); String boundary = "-" + contentType.SubString (index + 9); String endBoundary = boundary + "-"; // 요청 개체에서 스트림을 가져옵니다. servletInputStream sis = request.getInputStream (); // 1 줄을 읽습니다. name.trim (). length ()> 0) {if (fileflag) {bos.flush (); baos.close (); bos.close (); baos = null; bos = null; uddfilearr.add (fname);} else {obj = paramht.get. {al = (arraylist) obj;} al.add (value); system.out.println (value); paramht.put (name, al);}} name = new String (); value = new String (); fileflag = false; fname = new String (); rtnpos = sis.readline (buffs.lengs, 0, buffs.length); 새 문자열 (buffs, 0, rtnpos); if (strbuff.tolowercase (). startStwith ( "content-disposition : form-data;")) {int nindex = strbuff.tolowercase (). indexof ( "name =/" "); int nlastindex = strbuff.tolowercase (). strbuff.substring (nindex + 6, nlastindex);} int findex = strbuff.tolowercase (). indexof ( "filename =/" "); if (findex! = -1) {fileflag = true; int flastindex = strbuff.tolowercase (). indexf ("/"", findex + 10); flastIndex); fname = getFilename (fname); if (fname == null || fname.trim (). length () == 0) {fileflag = false; sis.readline (buffs, 0, buffs.length); sis.readline (buffs, 0, buffs.length); sis.readline (buffs, 0, buffs.length); 계속;} else}}; buffs.length); sis.readline (buffs, 0, buffs.length);}}} else if (strbuff.startswith (endboundary)) {if (name! = null && name.trim (). length ()> 0) {if (fileflag) {bos.flush (); baos.close (); bos.close (); null; uddfilearr.add (fname);} else {object obj = paramht.get (name); arraylist al = new arraylist (); if (obj! = null) {al = (arraylist) obj;} al.add (value); paramht.put (name, al);}} else {if (fileflag) {if (if) {if (vallag)}}. && bos == null) {tmpfile = 새 파일 (uploadpath + fname); baos = new FileoutputStream (tmpfile); bos = new bufferedoutputstream (baos);} bos.write (buffs, 0, rtnpos); baos.flush (); strbuff); value = value + strbuff;}}}} catch (ioexception e) {status = 4;} reture status;} private int precheck () {int errcode = 0; if (request == null) return 1; if (uploadPath == null || upload.trim (). length () == 0) return 2; else {file tmpf = 새 파일 (uploadpath); if (! tmpf.exists ()) return 2;} 문자열 contenttype = request.getContentType (); if (contenttype.indexof ( "multipart/form -data") ==) return 3; return 3; 이름) {string value = ""; if (name == null || name.trim (). length () == 0) return value; value = (name) == null)? ":( String) ((arraylist) paramht.get (name)). name.trim (). length () == 0) return null; if (paramht.get (name) == null) return null; arraylist al = (arraylist) paramh.get (name); strart [] new Strize [)]; for (int i = 0; i <al.size ()); int getUpdFilesize () {return updfilearr.size ();} public String [] getUpdFilenames () {Strart [] strarr = new String [updfilearr.size ()]; for (int i = 0; i <updfilearr.size (); i ++) strarr [i); getFilename (String Input) {int findex = input.lastIndexof ( "//"); if (findex == -1) {findex = input.lastIndexof ( "/"); if (findex == -1) {input = input.substring (findex + 1);} private string (int put) index = input.indexof ( "."); date dt = new date (); simpledateformat sdf = new SimpledateFormat ( "yyyymmmddhhmmssss"); return input.substring (0, index) + sdf.format (dt) + input.substring (index);}}}}}}}}2. JSP 페이지에서 Java 클래스를 참조하십시오.
<%@page import = "com.vogoal.util.jspfileUpload"%> <%// jspfileupload jfu = new jspfileupload (); // 요청 객체 jfu.setRequest (request); // 업로드 된 파일 경로 jfu.setupload path ( "c : //"); jfu.process (); // 형식 문자열에서 다른 입력 제어 매개 변수의 값을 가져옵니다. 문자열 username = jfu.getParameter ( "username"); // 동일한 매개 변수에 대한 여러 입력 컨트롤이있는 경우 배열 문자열을 반환 [] usernamearr = jfu.getParameters ( "username"); jfu.getupdfilenames (); // 업로드 된 파일의 수를 얻습니다.이 메소드는 약간 쓸모가 없습니다 int filenumber = jfu.getupdfilesize (); // 다음은 테스트의 코드 출력입니다. // out.println ( "매개 변수 :" + username); // out.println ( "매개 변수 크기 :" + usernamearr.length); // out.println ( "filearr size :" + filearr.length); // if (filearr.length> 0) // out.println ( " + filear 0 :");
세 번째 요점 : struts2는 파일 업로드 및 다운로드를 구현합니다
1 단계 : Commons-FileUpload-1.2.1.jar 및 Commons-IO-1.3.2.jar 아래 웹 -INF/lib 아래를 추가하십시오. 이 두 파일은 http://commons.apache.org/에서 다운로드 할 수 있습니다.
2 단계 : 양식 테이블의 ENCTYPE를 다음과 같이 "multipart/form-data"로 설정하십시오.
자바 코드
공개 클래스 업하 {private file uploadImage; // 개인 문자열 uploadImageContentType; // 파일 유형 개인 문자열 uploadImageFilename; // 파일 이름 개인 문자열 책 이름; // 책 이름 개인 문자열 저장 제자; // 파일 저장 위치; // 속성 getter/setter public upload () {// 업로드 코드, i/o 운영 완료 "업로드" }}참고 : 양식의 파일 도메인은 동작의 세 가지 속성, 즉 파일 이름 및 파일 유형에 해당합니다. 이름 지정이 고정되어 있습니다. 파일 이름은 양식 (uploadImage)의 파일 도메인 이름과 동일해야합니다. 파일 이름은 파일 + filename 및 파일 유형 : File + ContentType입니다.
4 단계 : 업로드 작업을 struts.xml로 구성하십시오.
자바 코드
<action name = "업로드"> <param name = "savepath">/uploadfile </param> <result> /success.jsp </result> </action>
참고 : 서버에서 업로드 된 파일의 저장 디렉토리를 지정하려면 업로드 액션에서 SavePath 변수를 정의하고 해당 세터 및 getter 메소드를 추가하여 struts2가 /uploadfile 값을 SavePath 속성에 할당 할 수 있도록해야합니다.
수동 구성 파일 필터링 유형
<param name = "allowtypes"> image/bmp, image/png, image/gif, image/jpeg </param>
수동 구성 파일 크기 제한
<param name = "maximsize"> 1048576 </param>
Struts2의 파일 업로드 인터셉터를 사용하여 파일 필터링을 구현하십시오
struts2는 파일 업로드 인터셉터 -fileUpload를 제공합니다. 이 인터셉터를 구성하면 업로드 된 파일의 필터링을 쉽게 달성 할 수 있습니다.
FileUpload 인터셉터를 구성 할 때는 두 가지 매개 변수를 지정할 수 있습니다.
alluctypes : English Comma (,)로 분리 된 업로드 할 수있는 파일 유형을 지정합니다.
최대 규모 : 바이트로 업로드 할 수있는 파일 크기를 지정합니다.
팁 : FileUpload 인터셉터를 구성하면 파일 필터링을 쉽게 구현할 수 있습니다. 파일 필터링이 실패하면 시스템이 입력 논리보기로 자동 전송됩니다. 따라서 입력이라는 이름의 논리보기는 작업에 대해 구성되어야합니다. 또한 DefaultStack의 인터셉터 참조는 작업에 대해 구성해야합니다.
struts2의 인터셉터를 사용하여 다음과 같이 파일 필터링 구성을 구현하십시오.
<action name = "uploadfileAction"> <interceptor-Ref name = "defaultStack"> <!-"defaultStack"> <!-다중 사용으로 업로드 할 수있는 파일 유형을 구성하고 "-"-> <param name = "fileUpload.allowedTypes"> image/bmp, image/png, image/gif, image/jpeg, 이미지/pjpg, 이미지/x-png, 이미지/pjpg, 이미지/bmp. <!-업로드 할 수있는 파일 크기를 구성, 단위 바이트,이 예제는 다음과 같습니다. 1MB-> <param name = "fileUpload.maxumSize"> 1048576 </param> </interceptor-ref> <result name = "input">/jsp/onefilefileupload.jsp </result> <result name = "/rets/rects."> result. ">
사용자가 업로드하지 않으면 특정 프롬프트 메시지가 있습니다. struts2에서 <s : fielderror/> 태그를 사용하여 오류 메시지를 페이지에 출력하십시오.
참고 : struts2 오류 프롬프트 정보를 사용하려면 파일을 업로드하는 조치 클래스는 ActionSupport를 상속해야합니다. 그렇지 않으면 struts2는 출력 오류 프롬프트 정보 기능을 제공하지 않습니다.
정보 출력을 사용자에게 저장하기 위해 리소스 파일 (.properties)을 구성 할 수 있습니다.
struts.messages.eror.file.too.large : 업로드 파일 크기가 설정 값을 초과하면 struts2가 키에 해당하는 프롬프트 정보를 출력합니다.
struts.messages.error.content.type.not.allowed : 업로드 된 파일 유형이 설정 값을 충족하지 않으면 struts2가 키에 해당하는 프롬프트 정보를 출력합니다.
struts.messages.error.uploading : 파일을 업로드 할 때 알 수없는 오류가 발생하면 struts2는 키에 해당하는 프롬프트 정보를 출력합니다.
또한 Resource 파일을 struts.xml 파일로 구성해야합니다. 다음으로 리소스 파일을 봐야합니다. 이미 중국어가 포함되어 있습니다. 우리는 그것을 변환 한 다음 프로젝트로 구성해야합니다.
struts.xml에서 리소스 파일을 설정하십시오.
<constant name = "struts.custom.i18n.resources"value = "message"/> 또는 <constant name = "struts.custom.i18n.resources"value = "messages_zh_cn"/>
원본 리소스 파일을 지원하는 것로 변환하려면 avative2ascii d :/messages.properties d : properties d :/messages_zh_cn.properties 명령을 사용하십시오.
참고 : 자원 파일의 이름 접미사 인 International을 유지하십시오. *_ZH_CN + 파일 확장.
여러 파일을 업로드하는 원리는 위와 동일하지만 여러 파일 필드의 이름 속성 이름은 동일해야하며,이를 수행하려면 <file>을 사용하여 사용해야합니다.
개인적 으로이 메소드를 사용하여 여러 파일을 업로드하는 것이 아니라고 생각합니다.
매우 좋은.
파일 다운로드 용 struts2
struts2는 스트림 결과 유형을 제공하며, 특히 파일 다운로드를 지원하는 데 사용됩니다. 스트림 결과 유형을 지정할 때 InputName 매개 변수를 구성 해야하는데, 이는 다운로드 된 파일의 입구 인 입력 스트림을 지정하는 입력 스트림을 지정해야합니다 (즉, 파일은이 항목을 통해 스트림에서 다운로드 할 수 있음).
파일 다운로드 동작을 구현하십시오
공개 클래스 Filedownloadaction Action {//이 속성 값은 구성 파일에 지정됩니다. struts2는 자동으로 주입합니다 (즉, 값을 할당). setter 및 getter 메소드를 제공해야합니다. 개인 문자열 입력 경로; // 다운로드 할 파일의 전체 경로를 지정합니다 (Path Name + File Name)/ * * 다운로드를 구현하는 작업 클래스는 InputStream 인스턴스를 반환하는 메소드를 제공해야합니다. <result ... // public inputStream getTargetFile ()의 해당 inputName 속성 값은 예외 {return servletActionContext.getServletContext (). getResourCeasStream (inputpath); } // 성공 문자열을 반환하는 사용자 요청을 처리하는 실행 메소드 공개 문자열 execute ()는 예외 {return "success"; }}struts.xml 파일의 해당 조치 구성
<action name = "download"> <!-다운로드 된 자원의 위치를 지정합니다-> <param name = "inputpath">/uploadfile/demo.txt </param> <!-결과 유형을 스트림으로 구성-> <결과 이름 = "success"= "stream"> <! </param <! file-> <param name = "inputname"> targetfile </param> <!-다운로드 된 파일의 다운로드 방법과 다운로드 시점에 저장된 파일 이름을 지정하십시오. 파일을 저장 할 때의 파일 이름에는 확장자가 있어야하며 확장자는 다운로드 유형의 아이콘을 표시해야합니다-> <param name = "contentDisposition"> 첨부; filename = struts2.txt </param> <!-다운로드 된 파일의 버퍼 크기를 지정하십시오.
위는 편집자가 소개 한 Java에서 파일 업로드 및 다운로드를 구현하기위한 세 가지 솔루션입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!