java下載字符串

  • 依賴 
 <dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>1.3.2</version>
 </dependency>
  • 工具類 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 下載工具類
 * @author czs
 * @date 2020-2-22 11:02:54
 */
public class DownloadUtils {

    /**
     * 根據字符串下載內容
     *
     * @param request  request
     * @param response response
     * @param fileName 下載的文件名
     * @param content  字符串內容
     * @throws IOException
     */
    public static void downloadByStringContent(HttpServletRequest request,
                                               HttpServletResponse response,
                                               String fileName, String content)
            throws IOException {
        //設置向瀏覽器端傳送的文件格式
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
            // firefox瀏覽器
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
			// IE瀏覽器
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
            // 谷歌
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        BufferedInputStream inp = null;
        OutputStream out = response.getOutputStream();
        try {
            inp = new BufferedInputStream(new ByteArrayInputStream(content.getBytes("utf-8")));
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inp.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inp != null) {
                inp.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

}
  • Controller
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/exportKtrAndKjb")
public void exportKtrAndKjb(@RequestParam String path, @RequestParam String type, HttpServletRequest request, HttpServletResponse response) throws Exception {
    String xml = xxxService.getXmlByXXX(path);
    String fileName = xxxService.getFileNameByXml(xml);
    DownloadUtils.downloadByStringContent(request, response, fileName, xml);
}
  • JavaScript
window.location.href= 'repository/exportKtrAndKjb.do?path='+ path + '&type=transformation';

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章