1. Prinsip unggahan file
1. Prasyarat untuk mengunggah file:
A. Metode bentuk bentuk harus diposting
B. Enctype dari formulir harus berupa multipart/form-data (ini menentukan metode permintaan pasca dan tipe data dari badan permintaan)
C. Jenis input yang disediakan dalam formulir adalah Domain Upload File Jenis File.
2. Gunakan komponen pihak ketiga untuk mencapai unggahan file
1. Commons-Fileupload Component:
JAR: Commons-Fileupload.jar
commons-io.jar
2. Kelas inti atau antarmuka
DiskFileItemFactory: Atur lingkungan
public void setsizethreshold (int sizethreshold): atur ukuran buffer. Standarnya adalah 10kb.
Saat file yang diunggah melebihi ukuran buffer, komponen fileupload akan mengunggah file menggunakan cache file sementara
public void setRepository (java.io.file repository): Atur direktori di mana file sementara disimpan. Secara default, direktori penyimpanan file sementara sistem.
ServletFileUpload: Kelas Upload Inti (Fungsi Utama: Parse Konten Tubuh dari Permintaan)
Boolean IsMultipartContent (httpservletRequest? Permintaan): Menentukan apakah enctype dari bentuk pengguna adalah tipe multipart/form-data.
Daftar Parserequest (permintaan httpservletrequest): Parse konten di badan permintaan
SetFilesizeMax (4*1024*1024); // Atur ukuran file tunggal yang diunggah
unggah.setsizeMax (6*1024*1024); // Setel ukuran file total
FileItem: mewakili bidang input dalam formulir.
boolean isFormfield (): apakah itu bidang normal
String getFieldName: Dapatkan nama bidang bidang normal
String getstring (): Dapatkan nilai bidang normal
InputStream getInputStream (): Dapatkan aliran input bidang yang diunggah
String getName (): Dapatkan nama file yang diunggah
Contoh: Pertama-tama buat folder file di direktori web-inf, yaitu, semua file harus diunggah di sini, yaitu untuk menghindari akses langsung oleh orang lain.
1. Dapatkan jalur file yang sebenarnya
String storePath = getSerVletContext (). GetRealPath ("/web-inf/file");
2. Mengatur lingkungan
DISKFILEITEMFACTORY FACTORY = DISKFILEITEMFACTORY baru (); // Di mana cache default dan tempat penyimpanan file sementara
3. Metode pengiriman formulir
boolean ismultipart = servletfileupload.ismultipartcontent (permintaan); if (! isMultipart) {System.out.println ("Metode Unggah Salah!"); kembali; }4. File Unggah Kelas Inti
SERVLETFILEUPLOAD UEDLOAD = SERVLETFILEUPLOAD baru (pabrik); 5. Analisis // Daftar Parse <FILEITEM> item = Upload.ParSequest (permintaan); untuk (item FileItem: item) {if (item.isFormField ()) {// Bidang normal, String FieldName Diserahkan oleh Form = Item.GetFieldName (); // Nama bidang dari informasi Formulir String FieldValue = item.getString (); // Bentuk informasi Nilai bidang System.out.println (FieldName+"="+FieldValue); } else // file pemrosesan {inputStream in = item.getInputStream (); // unggah nama file c: /users/administrator/desktop/a.txt name string = item.getName (); // Hanya perlu A.txt string filename = name.substring (name.LastIndexof ("//")+1); // Bangun stream output String StoreFile = StorePath+"//"+FileName; // Unggah alamat simpan file outputStream out = new FileOutputStream (StoreFile); byte [] b = byte baru [1024]; int len = -1; while ((len = in.read (b))! =-1) {out.write (b, 0, len); } in.close (); // tutup aliran out.close (); }}Tulis formulir
<%@ page language = "java" import = "java.util.*" pageEncoding = "UTF-8"%> <%string path = request.getContextPath (); string basepath = request.getscheme ()+": //"+request.getServername ()+":"+request.getserverport ()+PATPERPORT.POCPY ";"; "+": "+"+"+"; "+"; "+"; "+"; "+"; "+"; "+"; "publporpy ();"+";"+";"+";" publport ";"); "+"; "+"; docty/doctypath (): "+request. "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP '1.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href = "styles.css">-> </head> <body> <form Action = "$ {pageContext.Request.contextPath}/servlet/unggah servlet2" Metode = "POST" ENCTYPE = "Multipart/Form-Data"> Nama USERName <Input = "Teks" name = "UserName" name = "f1"/> <br/> <input type = "file" name = "f2"/> <br/> <input type = "kirim" value = "save"/> </form> </body> </html>Tulis servlet pengiriman: unggahServlet2
Paket com.liuzhen.upload; import java.io.fileOutputStream; import java.io.ioException; import java.io.inputstream; impor java.io.outputStream; impor java.util.list; impor javax.servlet.servletexception; impor javax.listsvax. javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletResponse; import org.apache.commons.fileupload.fileitem; impor org.apache.commons.fileupload.fileuPoadeM; org.apache.commons.fileupload.disk.diskFileItemFactory; impor org.apache.commons.fileupload.servlet.servletfileupload; // Pengantar keunggahan file Public UploadServlet2 memperluas httpservlet {public void DOGEG unggah PUBLICRPSRPS2 ServletException, ioException {// atur encoding revand.setcharacterencoding ("UTF-8"); response.setContentType ("Teks/html; charset = utf-8"); coba {// unggah file string storePath = getservercontext (). getRealPath ("/web-inf/file"); // Atur lingkungan DiskFileItemFactory Factory = DiskFileItemFactory baru (); // Hakim Metode Transmisi Formulir Formulir ENCTYPE = multipart/form-data boolean ismultipart = servletfileupload.ismultipartContent (permintaan); if (! isMultipart) {System.out.println ("Metode unggah salah!"); kembali; } Servletfileupload unggah = servletfileupload baru (pabrik); // Daftar Parse <FILEITEM> item = unggah.ParSeRequest (permintaan); untuk (item FileItem: item) {if (item.isFormField ()) {// Bidang normal, String FieldName Diserahkan oleh Form = Item.GetFieldName (); // Nama bidang dari informasi Formulir String FieldValue = item.getString (); // Bentuk informasi Nilai bidang System.out.println (FieldName+"="+FieldValue); } else // file pemrosesan {inputStream in = item.getInputStream (); // unggah nama file c: /users/administrator/desktop/a.txt name string = item.getName (); // Hanya perlu A.txt string filename = name.substring (name.LastIndexof ("//")+1); // Bangun stream output String StoreFile = StorePath+"//"+FileName; // Unggah alamat simpan file outputStream out = new FileOutputStream (StoreFile); byte [] b = byte baru [1024]; int len = -1; while ((len = in.read (b))! =-1) {out.write (b, 0, len); } in.close (); // tutup aliran out.close (); }}} catch (fileuploadException e) {lempar runtimeException baru (e); }} public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {doGet (permintaan, respons); }}File yang diunggah ada di aplikasi Tomcat.
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.