Lihat saja kodenya, komentarnya ada di dalamnya
Pertama -tama, web.xml
<? Xml Version = "1.0" encoding = "UTF-8"?> <Web-app Versi = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http:/www.w3.org/2001 =" http:/www.w3.org/200 XSI: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servet> <cription> Konfigurasikan pengontrol depan Springm. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-Mapping> <servlet-name> Unggah </servlet-name> <RURL-PATERS>/</RARL-PATERS> </Servlet-Mapping> <nilter> <deskripsi> Memecahkan masalah yang kacau dalam pengiriman parameter </description> <filter-name> characterEncodingutf8 </filter-name> <nilter-classics> org.springframework.wework.wework.wework.wework.wework.wework.wework. <Ilin-Param> <Param-name> Encode </param-name> <param-value> UTF-8 </param-value> </it-param> </tiler> <nilter-Mapping> <Tiler-name> KaraktereCodingutf8 </filter-name> <RURL-Pattern>/*</url-Pattern> </filter-phatping>
Di bawah ini terletak di //src//applicationcontext.xml
<? XML Versi = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmls xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemalocation = "http:smema http://www.springframework.org/schema/beans/spring-weans-3.2.xsd http://www.springframework.org/schema/mvc http:/www.springframework.org/schema/mvc http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/context/spring-context-3.2.xsd "> <!-component start component foomatic foomatic-context-3.2.xsd"> <!-start component automatic foomatic foomatic-context-3.xsd "> <!-start component automatic foomatic mekanik Mekanik Base-Paket)-> <!-Di sini Anda dapat merujuk ke artikel saya http://blog.csdn.net/jadyer/article/details/6038604-> <konteks: komponen-scan-package = "com.jadyer"/> <!-Fungsi annotasi pegas, ini akan secara otomatis, ini akan secara otomatis, ini akan secara otomatis annotasi Springmvc Fungsi Springmvc, ini akan secara otomatis, ini akan secara otomatis, Fungsi Springmvc Annotasi Springmvc, ini akan secara otomatis, ini akan secara otomatis, Fungsi Springmvc Annotation, ExceptionResolver --> <mvc:annotation-driven/> <!-- Since SpringMVC is set in web.xml to intercept all requests, it will not be read when reading static resource files --> <!-- Through this configuration, you can specify all resources that request or reference "/js/**" and will be found from "/js/" --> <mvc:resources mapping="/js/**" Lokasi = "/js/"/> <mvc: pemetaan sumber daya = "/unggah/**" location = "/unggah/"/> <!-Saat mengunggah file oleh springmvc, Anda perlu mengkonfigurasi prosesor MultiparTresolver-. bukan untuk satu file, tetapi untuk jumlah kapasitas semua file-> <name properti = "maxuploadsize" value = "800000"/> </ bean> <!-Ketika springmvc melebihi batas file unggah, itu akan melempar org.springframework.web.multipart.maxuploadsemeexceptEcceptEcceptEcceptEccept.web.web.multipart.maxuploadsizeExceedExceptEcceptEcceptEcceptEccept.web.multipart.maxuploadsexemedExceptEcceptEcceptEcceptEcceptEcceptEcceptEccepteed Informasi file, dan belum memasukkan metode pengontrol saat ini-> <bean id = "ExceptionResolver"> <name properti = "ExceptionMappings"> <sops> <!-Saat menemukan MaxuploadsizeExededException Exception, mereka akan secara otomatis melompat ke /web-inf/jsplexedException, secara otomatis melompat ke /web-inf. key = "org.springframework.web.multipart.maxuploadsizeExededException"> error_fileupload </prop> </props> </preate> </ bean> <bean> <name properti = "value".
Berikut ini adalah halaman prompt saat mengunggah konten file terlalu besar //web-inf//jsp//error_fileupload.jsp
<%@ halaman bahasa = "java" pageEncoding = "UTF-8"%>
<h1> File ini terlalu besar, silakan pilih kembali </h1>
Di bawah ini adalah halaman unggah untuk memilih file index.jsp
<%@ halaman bahasa = "java" pageEncoding = "UTF-8"%> <!-Ini tidak dapat disingkat sebagai <skrip tipe = "text/javaScript" src = ".." // js/jQuery-1.10.2.min.js "> </script> <script type =" teks/javascript " src = "<%= request.getContextPath ()%>/js/ajaxfileupload.js"> </script> <script type = "text/javascript" src = "<%= request.getContextPath ()%>/js/ajaxfileUpload. AjaxfileUpload () {// Gambar ditampilkan saat mengunggah file, dan unggahan file diselesaikan untuk menyembunyikan gambar // $ ("#loading"). AjaxStart (function () {$ (this) .show ();}). AjaxComplete (function () {$ (this) .hide (); //The server address of the file upload operation (the parameters can be passed, and it has been tested personally) url:'${pageContext.request.contextPath}/test/fileUpload?uname=Xuanyu', secureuri:false, //Whether secure commit is enabled, the default is false fileElementId:'myBlogImage', //The id attribute dataType:'text', // Format yang dikembalikan oleh server dapat berupa JSON atau XML, dll. Sukses: Fungsi (data, status) {// Fungsi pemrosesan data = data.replace ("<pe>", ''); // AjaxfileUpload akan menambahkan akhiran <pr Pre> teks </pe> ke konten teks yang ditanggapi kembali server. data = data.replace ("</pr Pre>", ''); data = data.replace ("<pr Pre>", ''); data = data.replace ("</pr Pre>", ''); data = data.replace ("</pr Pre>", ''); // Dalam contoh ini, setelah file unggahan selesai, server akan kembali ke latar depan [0`filePath] if (data.substring (0, 1) == 0) {// 0 berarti mengunggah dengan sukses (superhes jalur file setelah unggahan) (1 berarti kegagalan ("SUPLACH DACKRIPTION) $ (" IMG [ID = 'Upload)). $ ('#hasil'). html ("Upload gambar berhasil <br/>"); } else {$ ('#hasil'). html ('unggahan gambar gagal, coba lagi!!'); }}, error: function (data, status, e) {// fungsi pemrosesan $ ('#hasil'). html ('unggahan gambar gagal, coba lagi !!'); }});} </script> <div id = "result"> </div> <img id = "unggahimage" src = "http://www.firefox.com.cn/favicon.ico"> <input type = "file" id = "myBlogimage" name = "myfiles"/<"input =" file "=" myBlogimage "name =" myfiles "/<" "" my -inpip = "MyBlogImage" name = "MyFiles"/<"MyPAID"/<"MYPICE"/"MYPLOAD" NOVELT "NOVAL"/"MYPUT"/"MYPUT" NAME "/" MYPICE "NOVING" NAME = "MYFILE"/"MYPUT" MYPUT "NOVING" OnClick = "AjaxfileUpload ()"/> <!-Pengantar situs resmi AjaxfileUpload: http://phpletter.com/our-projects/ajaxfileupload/introduction: Plug-in AjaxfileUpload dapat mencapai file penguapan bebas refresh, dan mudah digunakan. Ini memiliki banyak pengguna. Sangat layak merekomendasikan: urutan memperkenalkan JS (tergantung pada jQuery) dan tidak ada formulir di halaman (hanya memicu metode jaxfileupload () ketika tombol diklik) kesalahan umum dan solusi adalah sebagai berikut 1) Sintakserror: hilang; before statement -- check whether the URL path can be accessed 2) SyntaxError: syntax error -- check whether the JSP file that handles the submission operation has syntax error 3) SyntaxError: invalid property id --check whether the property ID exists 4)SyntaxError: missing } in XML expression --check whether the file domain name is consistent or not 5) Other custom errors --check whether the parameters are correct by directly printing the Variabel $ error, yang jauh lebih nyaman daripada kesalahan kesalahan tidak valid di atas -> Akhirnya, FileuploadController.java yang menangani unggahan file
Paket com.jadyer.controller; import java.io.file; impor java.io.ioException; import java.io.printwriter; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservlete; org.springframework.stereotype.controller; impor org.springframework.web.bind.annotation.requestmapping; impor org.springframework.web.bind.annotasi. SpringMVC uses commons-fileupload implementation, it must first introduce its components into the project* 2) Configure the MultipartResolver processor in the SpringMVC configuration file (the attribute restrictions on uploaded files can be added here) * 3) Add the MultipartFile parameter to the Controller method (this parameter is used to receive the content of the file component in the form) * 4) Write the foreground form (note enctype = "multipart/form-data" dan <input type = "file" name = "****"/>)*ps: karena ajaxfileupload.js digunakan di sini untuk mencapai unggahan bebas refresh, formulir tidak digunakan dalam contoh ini* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Spring-Context-3.2.4.release.jar * Spring-core-3.2.4.release.jar * Spring-Expression-3.2.4.release.jar * Spring-jdbc-3.2.4.release.jar * Spring-ox-3.2.4. Spring-Web-3.2.4.release.jar * Spring-Webmvc-3.2.4.release.jar * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- After uploading the file, return to the foreground [0`filepath], 0 means uploading successfully (sequent to the uploaded file path), 1 means failure (sequent to the failure description) */ @RequestMapping(value="/fileUpload") public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest Permintaan, respons httpservletResponse) melempar ioException {// Anda dapat menerima parameter lain sambil mengunggah file system.out.println ("Usaha yang diterima [" + uname + "] Permintaan unggah file"); // Jika Anda menggunakan server Tomcat, file akan diunggah ke //%tomcat_home%// webapps // yourwebproject // unggah // folder // kelas commons.io.fileutils digunakan untuk menerapkan operasi unggah file di sini. Ini akan secara otomatis menentukan apakah /unggah ada. Jika tidak ada, itu akan secara otomatis membuat string realpath = request.getSession (). GetServletContext (). GetRealPath ("/unggah"); // Atur respons format data ke respons konten latar depan.setContentType ("Teks/polos; charset = UTF-8"); // Atur objek printwriter yang menanggapi printwriter konten latar depan = response.getWriter (); // Nama asli file unggahan (yaitu, nama file sebelum mengunggah) string originalFileName = null; // Jika Anda baru saja mengunggah satu file, Anda hanya perlu menerima file dalam jenis MultipartFile, dan tidak perlu secara eksplisit menentukan anotasi @RequestParam // Jika Anda ingin mengunggah beberapa file, Anda perlu menggunakan formasi frontfile, dan spesifik. " MyFiles, jika tidak, myFiles dalam parameter tidak dapat memperoleh semua file yang diunggah untuk (multipartfile myfile: myfiles) {if (myfile.isempty ()) {out.print ("1`Please Pilih file dan unggah"); out.flush (); kembali nol; } else {originalFileName = myfile.getoriginalfileName (); System.out.println ("File Nama Asli:" + AslifileName); System.out.println ("Nama file:" + myfile.getName ()); System.out.println ("Panjang file:" + myfile.getsize ()); System.out.println ("Jenis file:" + myfile.getContentType ()); System.out.println ("======================================================================================================================================== System.out.println ("========================================================================================================================================= =================================================================================================================================== =================================================================================================================================== =============================================================================================================================================== {System.out.println ("File [" + OriginalFileName + "] Gagal, trek tumpukan adalah sebagai berikut"); [D: /develop/apache-tomcat-6.0.36/webapps/Ajaxfileupload//upload/anger Birds.jpg] //system.out.println(realpath + "//" + originalfilead); //System.out.println (request.getContextPath () + "/unggah/" + originalFileName); // Rekomendasi [RealPath + "//" + OriginalFileName] tidak direkomendasikan // karena <img src = "file: //// d: /aa.jpg"> dapat ditampilkan oleh firefox di bawah windows, dan <img src = "d: /aa.jpg"> firefox tidak dikerjakan. "/unggah/" + originalFileName); out.flush (); kembali nol; }}Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.