Los ejemplos en este artículo comparten el código para descargar puntos de interrupción de Java para su referencia. El contenido específico es el siguiente
1. Código Java
// Implementar el archivo downloadFile () {file dir = new File (FilePath); // Obtener la ruta de archivo if (! Dir.exists ()) {system.out.println ("error de ruta de archivo"); log.debug ("Error de ruta de archivo"); return "falló"; // dirección si existe un archivo o carpeta} archivo downloadfile = nuevo archivo (dir, nombre de archivo); // Busque el archivo if (! dir.isfile ())) {system.out.println ("El archivo no existe"); log.debug ("El archivo no existe"); return "falló"; // determinar si el archivo o la carpeta existe} try {downloadFileranges (downloadfile); } Catch (ClientAbortException e) {System.out.println ("Conexión terminado"); log.debug ("Conexión terminada"); } catch (ioException e) {E.PrintStackTrace (); } return null; } private void downloadFileranges (archivo de descarga de archivo) lanza IOException {// tamaño de archivo para descargar largos fileLength = downloadFile.length (); // Tamaño del archivo descargado Long PastLength = 0; // si descargar el tren expreso, de lo contrario es un trueno u otro booleano isFlashget = true; // se usa para registrar el número de bytes finales que deben descargarse (truenos u otras descargas) Long Lenend = 0; // Se utiliza para registrar la cadena de rango de datos requerida por el cliente para descargar String Rangytes = request.getheader ("rango"); // se usa para leer y escribir aleatoriamente archivos RandomAccessFile RAF = NULL; OutputStream OS = NULL; OutputStream output = null; byte b [] = nuevo byte [1024]; // Si la solicitud de descarga del cliente contiene el rango if (null! = Rangytes) {// Código de retorno 206 Respuesta.SetStatus (httpservletResponse.sc_partial_content); rangebytes = request.getheader ("rango"). reemplazar ("bytes =", ""); // juzga el modo de cadena de rango if (rangebytes.indexof (' -') == rangebytes.length () - 1) {// No hay número de byte final, rápido isFlashget = true; rangebytes = rangebytes.substring (0, rangebytes.indexof ('-')); PastLength = long.parselong (rangebytes.trim ()); } else {// thunder descargar isFlashget = false; String startBytes = Rangytes.substring (0, rangebytes.indexof ('-')); String endbytes = rangebytes.substring (rangebytes.indexof ('-') + 1, rangebytes.length ()); // segmento de archivo descargado PastLength = Long.parselong (startBytes.trim ()); // El número de bytes de archivos que deben descargarse (comenzar desde el segmento de archivos descargado) lenend = long.parselong (endbytes); }} // Notificar al cliente que permita que los puntos de interrupción se transmitan continuamente, el formato de respuesta es: Aceptación de rangos: bytes Respuesta.Setheader ("Aceptar rangos", "bytes"); // Response.reset (); // Si es la primera descarga, el estado predeterminado es 200, y el formato de respuesta es: http/1.1 200 ok if (0! = PastLength) {// Content Range String String ContentRange = ""; // Formato de respuesta // Rango de contenido: bytes [Byte de inicio del bloque de archivos]-[Tamaño total del archivo-1] || [tamaño total del archivo] if (isFlashget) {contentRange = new StringBuffer ("bytes") .Append (new Long (PastLength) .ToString ()). Append ("-"). .Append ("/"). Append (new Long (Filelength) .ToString ()) .ToString (); } else {contentRange = new StringBuffer (rangeBytes) .Append ("/") .Append (new Long (Filelength) .ToString ()). ToString (); } respuesta.setheader ("Rango de contenido", contentRange); } Cadena filename = getdownloadChineseFileName (nombre de archivo); respuesta.setheader ("Disposición de contenido", "Adjunto; FileName =" + FileName + ""); // El formato de la respuesta es: Response.SetContentType ("Application/Octet-stream"); Respuesta.AddHeader ("Content-longitud", string.valueOf (fileLength)); intente {OS = Response.getOutputStream (); salida = new BufferedOutputStream (OS); RAF = new RandomAccessFile (downloadfile, "r"); // omita los bytes descargados Raf.seek (PastLength); if (isFlashget) {// expresar etc int n = 0; while ((n = raf.read (b, 0, 1024))! = -1) {output.write (b, 0, n); }} else {// Thunder, etc. while (raf.getFilePointer () <lenend) {output.write (raf.read ()); }} output.flush (); } Catch (ioException e) { /*** Al escribir datos, se lanzan excepciones como ClientAbortexception* porque el cliente cancela la descarga y el servidor continúa escribiendo datos en el navegador. Esto es normal. Especialmente para el software de clientes que chupan sangre como Thunder. * Obviamente hay un hilo de lectura de bytes = 1275856879-1275877358. * Si la lectura no se completa en un corto período de tiempo, Thunder comenzará el segundo y el tercero nuevamente. . . El hilo lee el mismo segmento de bytes hasta que un hilo termina de leer. Thunder matará * otros hilos que están descargando el mismo segmento de bytes, abortan a la fuerza a la lectura de bytes, lo que hace que el servidor arroje ClientAbortexception. * Entonces, ignoramos esta excepción*/} finalmente {if (output! = Null) {output.close (); } if (raf! = null) {raf.close (); }}} cadena privada getdownloadChineseFileName (String ParamName) {String downloadChineseFileName = ""; Pruebe {downloadChineseFileName = new String (paramName.getBytes ("GBK"), "ISO8859-1"); } catch (UnsupportedEncodingException e) {E.PrintStackTrace (); } return downloadchineseFileName; } public String getFilePath () {return filePath; } public void setFilePath (string filepath) {this.filePath = filePath; } public String getFileName () {return FileName; } public void setFileName (string filename) {this.fileName = filename; } public httpservletRequest getRequest () {solicitud de retorno; } public httpservletResponse getResponse () {Respuesta de retorno; } 2. Struts Sección <Br /> Copie el código de la siguiente manera: <Action name = "downloadfile" método = "downloadfile">
<Result name = "fallido" type = "redirectation"> showDownloadFileNAmelist </resultado>
</acción>
3. Parte de JSP
La copia del código es la siguiente: <td> <a href = "downloadfile? FileName = $ {FileMap.Key} && filePath = $ {FileMap.Value}"> Descargar archivos </a> </td>