여기서는 서블릿 기반 파일 비동기 업로드를 사용합니다. 나는 말도 안되는 말을하지 않고 코드를 업로드하지 않습니다. . .
package com.future.zfs.util; import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.iterator; import java.util.list; import javax.servlet.servletexception; import javax.servlet.httplet.httpervlet.httpervlet; javax.servlet.http.httpervletrequest; import javax.servlet.http.htttp.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.fileuploadbase.sizelimitexeceededexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload (serial file -filertels) httpservlet {Final Long max_size = 10 * 1024 * 1024; // 최대 업로드 된 파일을 10m으로 설정하십시오. { "jpg", "jpeg", "gif", "txt", "doc", "docx", "mp3", "wma", "m4a", "xls"}; public fileUploadServlet () {super (); } public void destroy () {super.destroy (); } @override Protected Void Service (httpservletrequest 요청, httpservletResponse 응답) servletexception, ioexception {response.setContentType ( "text/html"); // 인코딩을 UTF-8로 설정하여 중국어 문자가 응답을 표시하도록합니다 .SetchAracterEncoding ( "UTF-8"); // 하드 디스크 파일 공장을 인스턴스화하여 업로드 구성 요소 ServletFileUpload DiskFileItemFactory DFIF = New DiskFileItemFactory (); dfif.setsizethreshold (4096); // 파일을 업로드 할 때 파일을 임시로 저장하는 데 사용되는 메모리 크기를 설정하십시오. 4K는 다음과 같습니다. 하드 디스크 dfif.setRepository (새 파일 (requealpath ( "/") + "uploadtemp")); // 임시 파일이 저장되는 디렉토리를 설정하고, 웹의 루트 디렉토리 하에서 업로드 템플렛 디렉토리에 대한 업로드 템플렛 디렉토리에 대한 업로드 템플릿 (Instantiate)의 업로드 디렉토리 = 새로운 ServleTupif (new servletfif); // 최대 업로드 크기를 설정합니다. printwriter out = response.getwriter (); // 요청 목록에서 모든 업로드 필드 목록을 가져옵니다. filElist = null; try {filelist = sfu.parserequest (요청); } catch (fileUploadeXception e) {// 파일 크기 처리 너무 큰 예외 처리 (e instanceof sizelimiteXecedeDexception) {out.println ( "{usmer : '파일 크기가 지정된 크기를 초과합니다 :"+max_size+"byte'}"); 반품; } e.printstacktrace (); } // 파일 업로드가 없음 if (fileList == null || filElist.size () == 0) {out.println ( "{메시지 : '파일 업로드'}"); 반품; } // 업로드 된 모든 파일을 가져옵니다. iterator fileitr = filelist.iterator (); // 모든 파일을 루프 while (fileitr.hasnext ()) {fileitem fileitem = null; 문자열 경로 = null; 긴 크기 = 0; // 현재 파일을 가져옵니다 FileItem = (fileItem) fileitr.next (); // 업로드 된 도메인의 파일 도메인 대신 간단한 양식 필드를 무시합니다 (<input type = "text" /> 등) if (fileitem == null || fileItem.isformfield ()) {계속; } // 파일의 전체 경로를 가져옵니다. path = fileItem.getName (); // 파일 크기를 가져옵니다. 크기 크기 = fileItem.getSize (); if ( "".equals (path) || size == 0) {out.println ( "{메시지 : '파일 업로드'}"); 반품; } // 제거 된 경로의 파일 이름을 가져옵니다. 문자열 t_name = path.substring (path.lastIndexof ( "//") + 1); // 파일 확장을 가져옵니다 (전체 이름은 확장자없이 얻을 수 있습니다) 문자열 t_ext = t_name.substring (t_name.lastIndexof ( ".") + 1); // 지정된 파일 형식 외부에서 파일 유형이 거부됩니다 int allowflag = 0; int allendextCount = allowType.length; for (; allowflag <allendextCount; allowflag ++) {if (alc } if (allowflag == allendExtCount) {문자열 메시지 = ""; for (allowflag = 0; allowflag <allendextCount; allowflag ++) {message+= "*." + allowtype [allowflag] + ""; } out.println ( "{메시지 : '다음 유형의 파일"+message+"'}")을 업로드하십시오); 반품; } long now = System.CurrentTimeMillis (); // 시스템 시간 문자열 접두사에 따라 업로드 후 저장된 파일 이름을 생성합니다. prefix = string.valueof (지금); // 저장된 최종 파일의 전체 경로는 웹 U_NAME = request.getRealPath ( "/") + "ubload/" + prefix + "의 업로드 디렉토리에 업로드 디렉토리에 저장됩니다. + t_ext; // 원래 파일 이름 경로 = request.getRealPath ( "/") + "Upload/" + Path; try {// fileitem.write (새 파일 (path))을 저장합니다. Response.SetStatus (200); out.println ( "{message :/"파일 업로드 성공. " + prefix +". " + t_ext +"파일 크기 : " + size +"byte/"}"); } catch (예외 e) {e.printstacktrace (); }}}} web.xml
<Servlet> <Servlet-name> fileUploadServlet </servlet-name> <servlet-class> com.future.zfs.util.fileuploadservlet </servlet-class> </servlet> <servlet-name> fileUploadServlet </servlet-name> <url-pattern>/fileUplserver roaderoad roader adroad a
페이지 업로드
<%@ 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/tr/html4/loose.dtd"> <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"> <title> 여기에 제목 </title> <text/javascript " src = "js/jquery.js"> </script> <script type = "text/javaScript"src = "js/ajaxFileUpload.js"> </script> <script type = "text/javaScript"> 함수 ajaxfileUpload () {$ ( "#hoading").). }) // 파일 업로드를 시작할 때 이미지를 표시합니다 .ajaxComplete (function () {$ (this) .hide ();}); // 파일이 업로드 된 후 이미지 숨기기. $. ajaxFileUpload ({url : 'FileUploadServlet', // 'FileUploadServlet', // 일반적으로 Sudne To Walse, // 거짓으로 설정되었습니다. FileElementId : // 파일 업로드 공간의 ID 속성 <input type = "file"id = "file"name = "file"/> datatype : // 'json', // 'json', // 'json', // 'json', // json success : function (data, status) // 서버가 처리 함수 {//alert(data.message); $ ( '#myspan')는 struts2에 정의됩니다. if (typeof (data.error)! = 'undefined') {if (data.error! = '') {//alert(data.error); $ ( '#myspan'). html (data.message); } else {//alert(data.message); $ ( '#myspan'). html (data.message); }}}, 오류 : 함수 (데이터, 상태, e) // 서버 응답 실패 처리 함수 {// alert (e); $ ( '#myspan'). html (e); }}) false를 반환합니다. }. id = "myspan"> </span> <br/> <input type = "file"id = "file"name = "file"/<br/> <입력 유형 = "button"value = "ubload"onclick = "return ajaxfileupload ();"> <a href = "filedownloadservlet? filename.xls"> 테스트 파일, 테스트 파일. </body> </html> Servlet을 기반으로 업로드하기 위해 AjaxFileUpload를 사용하면 Response.setContentType ( "Text/Html")를 설정해야합니다. DataType : 'JSON'은 JSON으로 설정되어 있지만 여전히 응답을 설정해야합니다. 그렇지 않으면 서버가 반환 한 데이터는 얻을 수 없으며 대화 상자가 나타납니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.