如何从Java弹簧控制器上下载GUI中的CSV文件?

时间:2016-03-02 11:18:43

标签: java angularjs spring-mvc csv spring-boot

我是软件开发的新手,刚从大学毕业。做我的第一个大项目。

我正在尝试在用户选择项目的开始日期和结束日期时下载CSV文件,因此该文件应该返回project.csv,项目名称,日期从..到..

最重要的是我在点击" export"之后尝试从GUI下载文件。链接。我所知道的是我必须做一个弹簧控制器。我不得不错过一些因为它没有工作的部分。 我的java类是将csv文件写入我的C盘,但它没有下载部分。 CSV文件也应该从数据库写入用户计算机,而不是写入我的磁盘。

希望你了解我。如果情况清楚,请告诉我。

我的代码:

ExportController.java

    @RestController
    @RequestMapping("/config")
    public class ExportController {
         private String filePath = "C:\\test\\project.csv";
         private static final int BUFFER_SIZE = 4096;

        @Autowired
        private ExportService exportService;
        ServletContext context;

        @RequestMapping(value = "export/all", method = RequestMethod.POST)
        public String list(@RequestParam("startDate")String date, @RequestParam("endDate")String date2, HttpServletResponse response, HttpServletRequest request) throws ServletException, ParseException, IOException {
            DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
            Date date_obj = format.parse(date);
            Date date2_obj = format.parse(date2);

            // get absolute path of the application
            ServletContext context = request.getServletContext();
            String appPath = context.getRealPath("");
            System.out.println("appPath = " + appPath);

            // construct the complete absolute path of the file
            String fullPath = filePath;      
            File downloadFile = new File(fullPath);
            FileInputStream inputStream = new FileInputStream(downloadFile);

            // get MIME type of the file
            String mimeType = context.getMimeType(fullPath);
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }

            System.out.println("MIME type: " + mimeType);

            CsvWriterProject.savetofile();

            String csv = "Employee FN/LN: Eatrick Hughes Contract type: External, Activity: WAR, Effort date: 2016-02-17, Name: udfuhfd, Entity: BA, Start date: 2016-02-17, End_date: 2016-02-18";

            response.setContentType("application/csv");
            response.setHeader("Content-Disposition", "attachment; filename=project.csv"); 
            response.setHeader("Pragma", "public");
            response.setHeader("Expires", "0");
            response.setHeader("Content-Length", String.valueOf(csv.length()));
            response.setHeader("Content-type","application/csv"); 
        //  response.setContentType(mimeType);
        //  response.setContentLength((int) downloadFile.length());
            // get output stream of the response
            OutputStream outStream = response.getOutputStream();
            PrintWriter pw = new PrintWriter(outStream);
            pw.print(pw);


            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = -1;

            // write bytes read from the input stream into the output stream
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outStream.flush();
            outStream.close();
            return csv;


        }
    }

这是 angularJS

$scope.export_all = function(item){
         $http.post('config/export/all?startDate='+item.startDate+"&endDate="+item.endDate)
         .success(function(response) {
             $scope.export = response;

                });
    };

如果您需要更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:0)

你可以使用HttpServletResponse(javax.servlet.http.HttpServletResponse)

以下是示例代码:

package com.export.test;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping(value = "/exportTest")
public class ExportControllerTest {
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportStream(HttpServletResponse response) {
        try {
            String responseTosend = "Testing export for rest cliet";
            response.getOutputStream()
                    .write((responseTosend).getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

根据您的要求进行修改。 查看文档以获取更多信息https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html