Рубрики
Без рубрики

Стойки – пример загрузки файла с веб-сайта

– Стойки – скачать файл с примера веб-сайта

Чтобы разрешить пользователю загружать файл из вашего веб-проекта Struts, вы должны сообщить ” HttpServletResponse “, чтобы вернуть файл приложения вместо обычной HTML-страницы.

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=downloadfilename.csv");

На стороне сервера вы можете получить файл загрузки 3 различными способами

1. Файловая система

Получите его из файловой системы

FileInputStream in = 
  new FileInputStream(new File("C:\\filename.zip"));
2. Веб-путь проекта

Предположим, что ваш файл находится по адресу ” http://yourname.com/StrutsExample/upload/filename.zip “, а ” Пример распорок ” – это имя вашего проекта (контекст serlvet).

//jndi:/yourname.com/StrutsExample/upload/filename.zip
URL url = getServlet().getServletContext().getResource("upload/filename.zip");
InputStream in = url.openStream();
3. Массив байтов

Если вы извлекаете файлы или данные большого двоичного объекта из базы данных, они обычно возвращаются в виде массива байтов.

byte[] bytes = new byte[4096];
InputStream in = new ByteArrayInputStream(bytes);

1. Класс действий

Класс действий для возврата файла приложения вместо обычной HTML-страницы и получения “superfish.zip “файл для загрузки пользователем.

package com.mkyong.common.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DownloadFileAction extends Action{
	
   @Override
   public ActionForward execute(ActionMapping mapping, ActionForm form,
     HttpServletRequest request, HttpServletResponse response)
     throws Exception {
		
     //return an application file instead of html page
     response.setContentType("application/octet-stream");
     response.setHeader("Content-Disposition","attachment;filename=superfish.zip");
        
     try 
     {
       	//Get it from file system
       	FileInputStream in = 
      		new FileInputStream(new File("C:\\superfish.zip"));
        	
        //Get it from web path
        //jndi:/localhost/StrutsExample/upload/superfish.zip
        //URL url = getServlet().getServletContext()
        //               .getResource("upload/superfish.zip");
        //InputStream in = url.openStream();
        	
        //Get it from bytes array
        //byte[] bytes = new byte[4096];
        //InputStream in = new ByteArrayInputStream(bytes);

        ServletOutputStream out = response.getOutputStream();
        	 
        byte[] outputByte = new byte[4096];
        //copy binary content to output stream
        while(in.read(outputByte, 0, 4096) != -1){
        	out.write(outputByte, 0, 4096);
        }
        in.close();
        out.flush();
        out.close();

     }catch(Exception e){
    	e.printStackTrace();
   }

   return null;
  }
}

2. Страница JSP

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>





Download file from server - 
struts-tutorial.zip 


3. Страница JSP

Файл конфигурации распорок.







	
	
		
		
		
		
		
	


4. Проверьте это

http://localhost:8080/StrutsExample/DownloadPage.do

Оригинал: “https://mkyong.com/struts/struts-download-file-from-website-example/”