1. Analisis prinsip unggahan file
1. Prasyarat yang diperlukan untuk mengunggah file
A. Metode formulir harus diposting
B. Properti enctype dari formulir harus dari tipe multipart/form-data.
Nilai default enctype: Aplikasi/X-WWW-Form-Burlencoded
Fungsi: Beri tahu server ke jenis MIME dari teks permintaan
Aplikasi/X-WWW-Form-Urlencoded: Username = ABC & Kata Sandi = 123
ServletRequest.getParameter (nama string); Metode ini adalah metode yang secara khusus membaca jenis ini
multipart/form-data:
2. Gunakan komponen Commons-Fileupload untuk mengunggah file
A. Salin Paket JAR: Commons-Fileupload.jar commons-oo.jar
B. Prinsip Implementasi
3. Masalah kode sampah
A. Kode Sampah bidang biasa
Fileitem.getString (string charset); Pengkodean harus konsisten dengan klien
B. Nama file Cina yang diunggah kacau.
request.setcharacterencoding ("UTF-8"); Pengkodean harus konsisten dengan klien
4. Implementasi spesifik
Kode untuk unggahan meja depan.jsp adalah sebagai berikut
<%@ page language = "java" import = "java.util.*" pageEncoding = "UTF-8"%> <! Doctype html public "-// w3c // dtd html 4.01 transisi // en"> <html> <head> <titement> File unggahan </title> <"no-contition> <htp-" <htp-prePMl> <head> <titeme> file unggahan </title> <"no" http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "kedaluwarsa" content = "0"> <!-<link rel = "stylesheet" type = "text/css" href = "styles.cs">-</head> <body> action="${pageContext.request.contextPath}/servlet/UploadServlet3" method="post" enctype="multipart/form-data">name:<input name="name"/><br/>file1:<input type="file" name="f1"/><br/>file2:<input type="file" name="f2"/><br/>input type = "Kirim" value = "unggah"> </form> </body> </html>Latar Belakang Kode Servlet
Paket com.itheima.servlet; impor java.io.file; impor java.io.ioexception; impor java.io.printwriter; impor java.io.usupportedencodingException; impor java.util.list; impor java.util.util.uuid; impor javax.servlet; javax.servlet.http.httpservlet; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpServletResponse; org.apache.commons.fileupload.fileItem; org.apache.commons.fileupload.fileItem; org org.apache.commons.fileupload.fileitem; org.apache.commons.fileUdoAD.fileItem; org org org.apache.commons.fileupload.fileuploadException; impor org.apache.commons.fileupload.disk.diskfileItemFactory; impor org.apache.commons.fileupload.servlet.servletfileupload; impor org.apache.commons.commons. UnggahanServlet3 memperluas httpservlet {public void doGet (httpservletRequest, httpservletResponse response) melempar servletException, ioException {request.setcharacterencoding ("UTF-8"); response.setContentType ("teks/html; htmL; response.getWriter (); System.out.print (request.getRemoteAddr ()); boolean ismultipart = servletfileupload.ismultipartcontent (permintaan); if (! ismultipart) {lempar runimeException ("silakan periksa enctype properti dari bentuk Anda untuk mengkonfirmasi bahwa itu adalah multiMeException (" DiskFileItemFactory (); servletFileUpload parser = new servletFileUpload (dfif); // parser.setfilesizeMax (3*1024*1024); // Tetapkan ukuran unggahan satu file // parser.setsizemax (6*1024*1024); {items = parser.parsequest (request);} catch (fileuploadbase.filesizelimitexededException e) {out.write ("unggahan evelimexeededEcception e) {outrite." 6m "); return;} catch (fileuploadException e) {e.printstacktrace (); Lempar runtimeException baru ("Parse unggahan konten gagal, coba lagi");} // Proses konten yang diminta jika (item! = null) {for (item fileitem: item) {if (item.isformField ()) {processFormField (item);} lain {processuploadfield (item);}}}} {unggul ") (item) {unggah");}}} {unggul ") {item {unggul"); ProcessUploadField (item FileItem) {coba {string filename = item.getName (); // if (fileName! = null &&! filename.equals ("")) {filename = uuid.randomuuid (). tostring ()+"_"+filenameutil.getNameID (). Filenameutils.getextension (fileName); // mime type string contentType = item.getContentType (); if (contentType.startswith ("gambar/")) {// date now = new date (); // dateFormat df = new SimpleFormat ("yyyy-mm-dd"); // dfformat df = new SimpleFormat ("yyyy-mm-dd");//dfformat = new Sedem Direktori Menurut kode hash dari nama file string childDirectory = MakeChildDirectory (getserVletContext (). getRealPath ("/web-inf/file/"), fileName); string storedirectorypath = getServletcory (). getRealPath ("/web-inf/file/"+childdory (). File (storedirectorypath); if(!storeDirectory.exists()){storeDirectory.mkdirs();}System.out.println(fileName);ite(new File(storeDirectoryPath+File.separator+fileName));//Delete temporary file}}} catch (Exception e) {throw new RuntimeException("Upload failed, please try Lagi ");}} // Hitung string privat subdirektori yang disimpan MakeChildDirectory (String RealPath, String FileName) {int hashCode = filename.hashcode (); int dir1 = hashCode & 0xf; // Ambil 1 ~ 4 bit int int dir2 = (hashcode & 0xf0)>/ 0 ""+dir1+file.separator+dir2; file file = file baru (realpath, direktori); if (! file.exists ()) file.mkdirs (); return directory;} private void processFormField (fileitem item) {string fieldname = item.getFieldName (); // nama bidang fieldvale ("{string fieldname = get. catch (UnsupportedEncodingException e) {throw new RuntimeException("UTF-8 encoding is not supported");}System.out.println(fieldName+"="+fieldValue);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, tanggapan);}}5. tentang dokumen sementara
A. DiskfileItemFactory
public void setRepository (File Repository): Setel direktori di mana file sementara disimpan public void setsizethreshold (int sizethreshold): atur ukuran cache
B.
Saat mengunggah file, gunakan aliran IO untuk memprosesnya sendiri. Pastikan untuk menghapus file sementara setelah aliran ditutup. Fileitem.delete ()
Disarankan untuk menggunakan: FileItem.Writer (File f). File sementara akan dihapus secara otomatis.
6. Batasi ukuran file
A.
Servletfileupload.setFilesizeMax (3*1024*1024); // Atur ukuran unggahan file tunggal
B.
Servletfileupload.setsizeMax (6*1024*1024); // batas ukuran total saat mengunggah beberapa file
Di atas adalah kode contoh untuk commons Fileupload Implementasi File Unggah yang diperkenalkan oleh editor. Saya harap ini akan membantu semua orang. Jika Anda memiliki pertanyaan, silakan tinggalkan saya pesan dan editor akan membalas semua orang tepat waktu. Terima kasih banyak atas dukungan Anda ke situs web Wulin.com!