Ada dua jenis unduhan file web. Salah satunya adalah file tersebut ada di direktori situs web. Anda dapat mengunduhnya dengan langsung memasukkan jalur file di browser, seperti http://www.xxx.com/file.zip. Jenis lain adalah bahwa file tidak ada di direktori situs web atau file dihasilkan secara dinamis (laporan ekspor atau ekspor excel, dll.). Dalam hal ini, unduhan file perlu dicapai melalui outputstream respons. Downloadutils adalah kelas Alat Unduh File Web Java yang menyediakan berbagai metode statis untuk mengimplementasikan unduhan file.
paket com.rhui.util; impor java.io.bufferedInputStream; impor java.io.bufferedoutputStream; impor java.io.file; impor java.io.fileInputStream; impor java.io.ioException; impor java.io.inputstream; impor java.io.outputStream; impor java.net.urlencoder; impor javax.servlet.http.httpservletResponse; impor org.apache.commons.lang3.stringutils; / *** Kelas Unduh File*/ Kelas Publik Downloadutils {/ *** File Unduh Pengkodean* Pengkodean ini memberi tahu browser metode pengkodean nama file untuk mencegah kode yang kacau saat mengunduh nama file Cina*/ private static string encoding = "UTF-8"; / *** Unduh File* Respons @param* @param FilePath Path dari file di server, termasuk nama file*/ Unduh public static void (httpservletResponse respons, string filePath) {file file = file baru (filepath.toString ()); unduh (respons, file, null, encoding); } /*** Unduh file* @param Response* @param FilePath Path dari file di server, termasuk nama file* @param fileName nama file yang diunduh ke browser. Jika Anda tidak ingin nama file yang diunduh oleh browser sama dengan nama file di server, silakan atur parameter ini */ public static void download (httpservletResponse response, string filePath, string filename) {file file = file baru (filepath.toString ()); unduh (respons, file, nama file, encoding); } /*** Unduh file* @param Response* @param FilePath Path dari file di server, termasuk nama file* @param fileName nama file yang diunduh ke browser. Jika Anda tidak ingin nama file yang diunduh oleh browser sama dengan nama file di server, silakan atur parameter ini* @param encoding nama file encoding*/ public static void download (httpserVletResponse response, string filePath, string filename, string encoding) {file file = file baru (filePath.toStry); unduh (respons, file, nama file, encoding); } /** * Unduh file * @param Response * @param File File * @param FileName Nama file yang diunduh ke browser. Jika Anda tidak ingin nama file yang diunduh oleh browser sama dengan nama file di server, silakan atur parameter ini */ public static void download (httpservletResponse respons, file file) {unduh (respons, file, null, encoding); } /*** Unduh file* @param Response* @param File File* @param FileName Nama file yang diunduh ke browser. Jika Anda tidak ingin nama file yang diunduh oleh browser ke server, silakan atur parameter ini */ public static void download (respons httpservletResponse, file file, string fileName) {unduh (respons, file, nama file, encoding); } /*** Unduh file* @param Response* @param File File* @param FileName Nama file yang diunduh ke browser. Jika Anda tidak ingin nama file yang diunduh oleh browser sama dengan nama file di server, silakan atur parameter ini* @param encoding nama file encoding*/ public static void download (httpserVletResponse response, file, file string, string encoding) {if (file == null ||! File. } // Jika Anda tidak menentukan nama file untuk diunduh ke browser, gunakan nama default file if (stringutils.isblank (fileName)) {filename = file.getName (); } coba {inputStream adalah = FileInputStream baru (file); unduh (respons, is, nama file, encoding); } catch (ioException e) {e.printstacktrace (); }} / *** Unduh File* @param Response* @param adalah aliran input file* @param fileName nama file yang diunduh* @throws ioException* / unduhan public static void (httpservletResponse, inputStream adalah, string filename) {download (respons, adalah, nama file, encoding); } / *** Unduh File* @param Response* @param adalah aliran input file* @param fileName nama file yang diunduh* @param encoding format* / download public static void (httpserVletResponse response, inputStream is, string file, string encoding) {if (is == NULL || } BufferedInputStream bis = null; OutputStream OS = null; BufferedOutputStream bos = null; coba {bis = new bufferedInputStream (IS); os = response.getoutputStream (); BOS = BufferedOutputStream baru (OS); response.setContentType ("Application/Octet-stream; charset =" + encoding); response.setcharacterencoding (pengkodean); response.setHeader ("konten-disposisi", "lampiran; fileName ="+ urlencoder.encode (nama file, encoding)); byte [] buffer = byte baru [1024]; int len = bis.read (buffer); while (len! = -1) {bos.write (buffer, 0, len); len = bis.read (buffer); } bos.flush (); } catch (ioException e) {e.printstacktrace (); } akhirnya {if (bis! = null) {coba {bis.close (); } catch (ioException e) {}} if (is! = null) {coba {isClose (); } catch (ioException e) {}}}} public static string getEncoding () {return encoding; } public static void setencoding (string encoding) {downloadutils.encoding = encoding; }}Jika file disimpan di direktori non-situs di server
String filepath = "c: //file.zip"; Downloadutils.download (respons, filepath);
Jika file adalah aliran input
// adalah arsip input stream // nama file adalah nama file yang diunduh oleh browser // encoding adalah nama file untuk mencegah kode yang kacau ketika ada bahasa Cina di file string filename = "file.zip"; String encoding = "UTF-8"; Downloadutils.download (respons, is, nama file, encoding);
Unduh File di Servlet
paket com.rhui.web.servlet; impor java.io.ioException; impor javax.servlet.servletException; impor javax.servlet.annotation.webservlet; impor javax.servlet.http.httpservlet; impor javax.servlet.http.httpservletRequest; impor javax.servlet.http.httpservletResponse; impor com.rhui.util.downloadutils; @Webservlet ("/download/servlet") Download kelas publik memperluas httpservlet {private static final long serialversionuid = 1l; Layanan void yang dilindungi (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {string filepath = "c: //file.zip"; Downloadutils.download (respons, filepath); }} PS: Unduh gambar (termasuk fungsi tautan anti-pencurian)
paket cn.itcast.day06.web.servlet; impor java.io.ioException; impor java.io.inputStream; impor java.io.outputStream; import java.net.urlencoder; impor javax.servlet.servletcontext; import javax.servlet.servletException; impor javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.htpserveVer; DownloadserVlet kelas publik memperluas httpservlet {public void doGet (httpservletRequest, httpservletResponse response) melempar servletException, ioException {// mengimplementasikan fungsi rantai anti-Theft // Get the Referer Header untuk menjelaskan di mana pengunjung datang dari string referer = request. if (referer == null ||! Referer.startswith ("http: // localhost")) {// Ini adalah tautan pencuri respons.sendredirect ("/day06/index.jsp"); kembali ; } // Pecahkan masalah respons respons respons Cina yang kacau.setContentType ("Teks/html; charset = utf-8"); // Atur pengkodean badan pesan // header pesan respons HTTP yang dikirim melalui protokol HTTP tidak dapat muncul dalam bahasa Cina Cina, Cina harus menjadi string filename yang dikodekan URL = urlencoder.encode ("Beauty.jpg", "UTF-8"); // beri tahu browser untuk membaca respons sumber daya. // Baca data gambar dan kirimkan ke IE Browser String WebPath = "/Download/Beauty.jpg"; // setara dengan jalur aplikasi web saat ini ServletContext servletContext = super.getSerVletContext (); InputStream in = servletContext.getResourceAsstream (webpath); OutputStream out = response.getoutputStream (); int len; byte [] buffer = byte baru [1024]; while ((len = in.read (buffer))! =-1) out.write (buffer, 0, len); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {doGet (permintaan, respons); }}