Pertama, izinkan saya memperkenalkan unggahan file
Kelas Entitas
impor java.sql.timestamp; / ** * * @Deskripsi File Unggah Entitas Kelas * */ kelas publik upfile {private string id; // ID kunci utama secara acak menghasilkan string privat uuidname; // nama uuid private string fileName; // nama file Private String savePath; // Simpan Path Private Timestamp Shoadtime; // Unggah Waktu Private String Deskripsi; // File Deskripsi Private String username; // nama pengguna upfile publik () {super (); } UpFile publik (ID String, String UUIDNAME, String FileName, String SavePath, Timestamp Shoadtime, String Deskripsi, String Username) {super (); this.id = id; this.uuidname = uuidname; this.filename = fileName; this.savepath = savePath; this.uploadtime = unggah waktu; this.description = description; this.username = nama pengguna; } public String getDescription () {return description; } public String getFileName () {return fileName; } public String getId () {return id; } public String getSavEpath () {return savePath; } waktu publik getUploadTime () {return unggahan waktu; } string publik getUserName () {return username; } public string getuuidname () {return uuidname; } public void setDescription (deskripsi string) {this.description = description; } public void setFileName (string fileName) {this.fileName = fileName; } public void setId (string id) {this.id = id; } public void setSavEpath (string savePath) {this.savePath = savePath; } public void setuploadtime (timestamp unggahtime) {this.uploadtime = unggah waktu; } public void setusername (string username) {this.username = username; } public void setUuidName (String uuidName) {this.uuidname = uuidname; }}halaman
<%@ halaman bahasa = "java" import = "java.util.*" pageEncoding = "UTF-8"%> <%string path = request.getContextPath (); String basePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerport ()+path+"/"; %> <! Doctype html public "-// w3c // dtd html 4.01 transisi // en"> <html> <adept> <base href = "<%= basepath%>"> <title> unggah jsp 'unggah = "no-conte =" no-conte = "no-conte =" no-conte = "no-conte =" no-conte = "no-conte =" no-conte = "no-conte> </title </title> <MetA http-equiv =" prag = "no-conte =" no-conte = "no-conte =" no-conte = "no-conte =" no-conte> </title </title </title> <MetA http-quiv = "no-conte =" no-conte = "no-conte =" no-conte> http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "kedaluwarsa" konten = "0"> <meta http-equiv = "kata kunci" konten = "kata kunci1, kata kunci2, koki"> <meta http http-equiv = "koki" ini = "ini" type="text/css" href="styles.css"> --> </head> <body> <h1> File Upload</h1> <form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data"> <table> <tr> <td> Upload username:</td> <td> <input type = "text" name = "username"/> </td> </tr> <tr> <td> unggah file: </td> <td> <input type = "file" name = "file"/> </td> </tr> <td> <td> Deskripsi: </td> </td> </ttr> <td> <td> Deskripsi: </td> </td> </TROWS = "5" Name = "Deskripsi"> </pteTarea> </td> </tr> <tr> <td> <input type = "kirim" value = "unggah start"/> </td> </tr> </ablef> </form> <vecontext. " Halaman </a> </body> </html> Servlet
impor java.io.ioException; impor javax.servlet.servletException; impor javax.servlet.http.httpservlet; impor javax.servlet.http.httpservletRequest; impor javax.servlet.http.httpservletResponse; impor org.apache.commons.fileupload.fileuploadbase.filesizelimitexededException; impor org.apache.commons.fileupload.fileuploadbase.sizelimitexededException; impor org.apache.commons.fileupload.servlet.servletfileupload; impor com.itheima.domain.upfile; impor com.itheima.exception.myexception; impor com.itheima.service.upfileService; impor com.itheima.service.impl.upfileServiceImpl; impor com.itheima.untils.webuntil; Public ColoadFileServlet memperluas httpservlet {public void doGet (httpservletRequest, respons httpservletResponse) melempar servletException, ioException {dopost (permintaan, respons); } public void dopost (permintaan httpservletRequest, httpservletResponse response) melempar servletException, ioException {// menilai apakah formulir tersebut terdiri dari beberapa bagian jika (! ServletFileupload.ismultipartContent (request)) {request.setattribute ("msg", "msgibute," mohon, "msgibute," msing, "msgeabetcontent (request)) {request.setattribute (" msg "," msg "," msg "," msgead, "msgead," msgeabetcontent (request) {request. dengan benar "); request.getRequestDispatcher ("/unggah.jsp"). Forward (Request, Response); kembali ; } // Jika itu adalah multi-bagian, dapatkan dan lintasi untuk mengembalikan objek unggahan file, berisi semua informasi yang diunggah, coba {upfile upfile = webuntil.upload (permintaan); UpFileService UpfileService = UpfileServiceImpl baru (); bendera boolean = upfileService.add (upfile); if (flag) {request.setAttribute ("msg", "unggah sukses"); request.getRequestDispatcher ("/unggah.jsp"). Forward (Request, Response); kembali ; } else {request.setAttribute ("msg", "Unggah gagal, coba lagi"); request.getRequestDispatcher ("/unggah.jsp"). Forward (Request, Response); kembali ; }} catch (FileSizelImitexedEdexception e) {E.PrintStackTrace (); request.setAttribute ("msg", "ukuran file tunggal, melebihi batas maksimum"); request.getRequestDispatcher ("/unggah.jsp"). Forward (Request, Response); kembali ; } catch (sizelimitexededException e) {e.printstacktrace (); request.setAttribute ("msg", "total ukuran file, melebihi batas maksimum"); request.getRequestDispatcher ("/unggah.jsp"). Forward (Request, Response); kembali ; }}}Peralatan
impor java.io.file; impor java.io.filenotfoundException; impor java.io.fileoutputStream; impor java.io.ioException; impor java.io.inputstream; impor java.io.outputStream; impor java.io.usupportedencodingException; impor java.util.arraylist; impor java.util.list; impor java.util.uuid; impor javax.servlet.http.httpservletRequest; impor org.apache.commons.fileupload.fileItem; impor org.apache.commons.fileupload.fileuploadbase; impor org.apache.commons.fileupload.fileuploadbase.filesizelimitexededException; impor org.apache.commons.fileupload.fileuploadexception; impor org.apache.commons.fileupload.progresslistener; impor org.apache.commons.fileupload.disk.diskfileItemFactory; impor org.apache.commons.fileupload.servlet.servletfileupload; impor com.itheima.domain.upfile; impor com.itheima.exception.myexception; /** * File upload tool class* @Describe TODO * */ public class WebUntil { /** * File upload method* @param request Pass the request parameter in * @return Return an Upfile object* @throws FileSizeLimitExceededException * @throws SizeLimitExceededException * @throws IOException */ public static Upfile upload(HttpServletRequest request) throws FileizelimitexededException, SizelimitexededException {upFile upFile = new UpFile (); ArrayList <String> FileList = initList (); Coba {// Dapatkan Disk Objek File DiskfileItemFactory Factory = New DiskFileItemFactory (); String tmp = request.getSession (). GetserVletContext (). GetRealPath ("/tmp"); System.out.println (TMP); // menginisialisasi setFactory (pabrik, TMP); // Dapatkan file unggah parser servletfileupload unggah = servletfileupload baru (pabrik); // inisialisasi parser setupload (unggah); // Dapatkan Daftar File <FILEITEM> DAFTAR = UEDLOAD.PARSEREQUEST (permintaan); // bepergian untuk (fileItem item: list) {// menilai apakah itu objek formulir biasa jika (items.isFormField ()) {// dapatkan nama unggah formulir string fieldname = items.getFieldName (); // nilai string fieldValue = items.getString ("UTF-8"); // menilai jika ("nama pengguna" .Equals (fieldName)) {// atur upfile.setusername (fieldValue); } else if ("description" .equals (fieldName)) {// atur atribut upfile.setDescription (fieldValue); }} else {// adalah file yang siap diunggah // dapatkan nama file string fileName = items.getName (); // menangani perbedaan dalam nama file yang diperoleh karena browser int yang berbeda index = filename.lastIndexof ("//"); if (index! =-1) {filename = filename.substring (index+1); } // menghasilkan nama file acak string uuidname = generateFileName (fileName); // Dapatkan jalur file yang diunggah string savePath = request.getSession (). GetserVletContext (). GetRealPath ("/web-inf/unggah"); // Dapatkan aliran input di inputStream objek permintaan di = items.getInputStream (); // Hancurkan file dan simpan di jalur yang berbeda, temukan jalur savePath = generaterandomdir (savePath, uuidname); // salin file unggahan (di, savePath, uuidname); String id = uuid.randomuuid (). Tostring (); upfile.setid (id); upfile.setsavepath (savePath); upfile.setuuidname (uuidname); upfile.setFileName (nama file); // hapus item cache.delete (); }}} catch (fileuploadbase.filesizelimitexededException e) {// Top lemparan pengecualian e; } catch (fileuploadbase.sizelimitexededException e) {// pengecualian lemparan e; } catch (FileuploAdException e) {E.PrintStackTrace (); } catch (UnsupportedEncodingException e) {e.printstacktrace (); } catch (ioException e) {e.printstacktrace (); } catch (Exception e) {E.PrintStackTrace (); } return upfile; } / *** Inisialisasi daftar file* @return* / private static arrayList <string> initlist () {arraylist <string> daftar = arraylist baru <string> (); list.add (". jpg"); list.add (". rar"); list.add (". txt"); list.add (". png"); daftar pengembalian; } /*** Salin File* Input Stream di @param di Item* @param savePath Simpan path* @param uuidname Nama file* /private static void unggahanfile (inputStream in, string savePath, string uuidname) {// dapatkan file file = file baru (savePath, uuidname); OutputStream out = null; coba {int len = 0; byte [] buf = byte baru [1024]; // Dapatkan stream output keluar = FileOutputStream baru (file); while ((len = in.read (buf))! =-1) {out.write (buf, 0, len); }} catch (FileNotFoundException e) {e.printstacktrace (); } catch (ioException e) {e.printstacktrace (); } akhirnya {coba {in.close (); } catch (ioException e) {e.printstacktrace (); } coba {out.close (); } catch (ioException e) {e.printstacktrace (); }}} /*** Hasilkan jalur penyimpanan acak* @param savepath save path* @param uuidname Nama uuid yang dihasilkan* @return* Gunakan kode hashc untuk menyelesaikan* /private static string generaterandomdir (string savePath, string uuidname) {// convert ke hashcode.out.println ("string uuidname) {// convert ke hashcode.out.println (" string uuidname) {// convert ke hashcode.out.println ("string uuidname (" System.out.println ("uuidname"+uuidname); int hashcode = uuidname.hashcode (); // Container StringBuilder SB = StringBuilder baru (); while (hashcode> 0) {// int 15 int tmp = hashCode & 0xf; SB.Append ("/"); SB.Append (TMP+""); HashCode = HashCode >> 4; } // pisahkan path string path baru = savePath+sb.toString (); System.out.println ("path"+path); File file = file baru (path); // menilai apakah ada jalur jika (! File.exists ()) {// buat file.mkdirs (); } // Kembalikan jalur pengembalian jalur simpan; } / *** Hasilkan nama file baru* @param uuidname nama id acak* @param nama file nama asli* @return* / string statis privat generateFileName (string filename) {string uuidname = uuid.randomuuid (). Tostring (); return uuidname.replace ("-", "") .toString ()+"_"+fileName; } / *** Parser Inisialisasi* @param mengunggah* / private static void setupload (servletfileupload unggah) {// atur karakter encoding unggah.setHeadEncoding ("UTF-8"); // atur unggah ukuran file.setFilesizeMax (1024*1024*20); // atur total unggah ukuran file.setsizeMax (1024*1024*50); // Setel progress listener unggah.setProgressListener (progressListener baru () {public void update (long pbytesread, long pcontentlength, int pitems) {System.out.println ("baca:"+pbytesread+","+pcontentLength+","+"+Pitems+"); *@param TMP Buffer Directory*/ Private Static Void SetFactory (DiskFileItemFactory Factory, String TMP) {/// Konfigurasikan Factory Buffer Nilai Inisialisasi. Unduh dua file
Servlet
Kelas Publik DownupFileServlet memperluas httpservlet {public void doGet (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {dopost (permintaan, respons); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {// dapatkan id string id = request.getParameter ("id"); // antarmuka lapisan bisnis upfileService upfileService = new UpfileServiceImpl (); // Temukan objek ini berdasarkan ID upfile upfile = upfileService.findupfilebyId (id); if (upfile == null) {return; } // Dapatkan nama asli file string fileName = upfile.getFileName (); // Jika ada bahasa Mandarin dalam nama file, itu perlu ditranskode, jika tidak, tidak akan ada nama file nama file = urlencoder.encode (nama file, "UTF-8"); // Mengubah nama string uuidname = upfile.getuuidname (); // Simpan Path String savePath = upFile.getSavEpath (); File file = file baru (savePath, uuidname); // Tentukan apakah file ada jika (! File.exists ()) {request.setAttribute ("msg", "file yang diunduh telah kedaluwarsa"); request.getRequestDispatcher ("/index"). Forward (Request, Response); kembali; } // Setel respons informasi header unduhan file respons.setHeader ("konten-disposisi", "lampiran; fileName ="+fileName); // Gunakan stream IO untuk output inputStream in = new FileInputStream (file); ServeLetoutputStream out = response.getoutputStream (); int len = 0; byte [] buf = byte baru [1024]; while ((len = in.read (buf))! =-1) {out.write (buf, 0, len); } in.close (); }}database
Buat database unggah_download_exercise; Gunakan unggah_download_exercise; Buat tabel upfiles (id varchar (100), // gunakan uuid untuk menghasilkan uuidname varchar (255), // uuid plus nama file asli nama file varchar (100), // nama file nyata savePath varchar (255), // save path unggah waktu timestamp, // unggah waktu deskripsi varchar (255), // dermal waktu) (dermam) (105), unggah waktu) (255), // dermal waktu) unggah waktu unggah, //sripse.
Di atas adalah konten Java yang relevan menggunakan Commos-Fileupload untuk mencapai pengunggahan file dan unduhan, saya harap ini akan membantu semua orang.