Saya tidak akan mengatakan banyak omong kosong, saya langsung ke intinya.
Diperlukan dua paket stoples:
Commons-Fileupload.jar
Paket JAR Commons IO (menggunakan commons-io-2.4.jar dalam artikel ini)
Gunakan Servlet untuk mengimplementasikan unggahan file.
Paket web.servlet; import java.io.ioException; import javax.servlet.servletException; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservlet; javax.servlet.http.httpservletResponse; import java.io.file; import java.util.iterator; import java.util.list; import org.apache.commons.fileupload.fileitem; import org.apache.apache.commons.fileupload.fileitem; Impor org.apache.apachecre org.apache.commons.fileupload.servlet.ServletFileUpload;/*** Servlet implementation class UploadServlet*/@WebServlet("/UploadServlet")public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;private String uploadPath = "D://temp"; // direktori untuk mengunggah file private string temppath = "d: // temp // buffer //"; // File File Sementara File TemppathFile; public void dopost (permintaan httpservletrequest, httpservletResponse response) melempar ioException, servletException {try {// membuat pabrik berbasis disk (factory/ factory factory (factory new factore (factore) factory; ConstraintsFactory.SetsizeThreshold (4096); // Atur ukuran buffer, di sini adalah 4KBFactory.SetRepository (TemppathFile); // Atur Direktori Buffer // Buat file baru unggah handlerServletFileUpload unggah = servletfileUpload (419430); // Atur ukuran file maksimum, berikut adalah 4MBlist <FILEItEM> items = unggah.Parsequest (request); // Dapatkan semua file iterator <FILEItEM> i = items.iterator (); while (i.hasnext ()) {fileItem fi = (fileItem) i.next (); string filename = fi. File (fi.getName ()); file saveDfile = file baru (unggahpath, fullfile.getName ()); fi.write (saveDfile);}}} {// halaman kesalahan dapat melompat (); unggahfile = file baru (unggahPath); if (! unggahfile.exists ()) {unggahfile.mkdirs ();} file temppathfile = file baru (Temppath); if (! Temppathfile.exists ()) {Temppathfile.mkdirs ();}}}}} {TemppathFile.Mkdirs () jsp
<%@ page language = "java" contentType = "text/html; charset = iso-" pageEncoding = "utf-"%> <! Doctype html public "-// wc // dtd html. Transisi // en" "http://www.w.org/tr/html/loose.dtd"><html><head><meta http-equiv =" tipe konten "content =" Text/html; charset = gb "> <itement> unggah file </title> </head> <! di <servlet-Mapping> di web.xml. --><form name="myform" action="UploadServlet" method="post"enctype="multipart/form-data">File:<br><input type="file" name="myfile"><br><br><input type="submit" name="submit" value="Commit"></form></body></html>
Ini hanya akan menerapkan fungsi unggahan file. Tentu saja, ini adalah yang paling mendasar, dan terus belajar.