java服務端spring框架 上傳下載文件的筆記

直接上代碼把,作爲自己的筆記方便複習查找
一、上傳文件的代碼:
(這裏把上傳的文件保存到了服務器本地的文件目錄中)
task_log_path 爲路徑的配置文件如下:

#任務日誌的路徑
task.log.path = D:/TaskLogStore

在application.properties中進行配置,在使用時用

 @Value("${task.log.path}")
    String task_log_path;

來進行獲取使用。

這裏的AllTask_Log是日誌文件的數據庫,由於日誌文件較大,儲存在數據庫中的某個字段可能會有未知的問題,保險起見,直接保存在了服務器的目錄文件夾下, AllTask_Log類只有兩個字段 String task_id和String task_log

    //任務執行日誌的上傳
    @PutMapping("/uploadLog")
    String uploadLog(@RequestBody AllTask_Log data)
    {
        int temp = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        FileOutputStream fos = null;

        List<Task_New>  currentAllTask = task_newService.getAll();
        List<Task_New>  result = currentAllTask.stream().filter(item->item.getId().equals(data.getTask_id())).collect(Collectors.toList());

        if (result==null || result.size()==0)
        {
            return "{\"state\":1000,\"msg\":\"日誌上傳失敗,task_id不存在任務列表中\"}";
        }


        //保存日誌文件到服務端
        String fileName = data.getTask_id()+"_"+sdf.format(new Date())+".log";
        String logFileSavePath = task_log_path + "/"+fileName;
        File  taskLogFile = new File(logFileSavePath);
        if (!taskLogFile.exists()){
            try {
                taskLogFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        byte[] bytes =new byte[1024];
        bytes = data.getTask_log().getBytes();
        int b = bytes.length;

        try {
            fos=new FileOutputStream(taskLogFile);
            try {
                fos.write(bytes,0,b);
                fos.write(bytes);
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }



        AllTask_Log currentLog = service.getById(data.getTask_id());
        if (currentLog ==null){
            data.setTask_log(fileName);
            temp = service.add(data);
        }else {
            data.setTask_log(fileName);
            temp = service.update(data);
        }

        if (temp>0)
        {
            return "{\"state\":200,\"msg\":\"日誌上傳成功\"}";
        }else {
            return "{\"state\":1000,\"msg\":\"日誌上傳失敗\"}";
        }
    }

二、下載日誌文件的代碼:
HttpServletResponse response 作爲一個網絡 傳輸協議,在參數列表的傳值裏是不會出現的

//任務日誌的下載
    @GetMapping("/downloadLog")
    void downloadLog(HttpServletResponse response,AllTask_Log data)throws IOException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fileName = data.getTask_id()+"_"+sdf.format(new Date())+".log";
        String downloadFileName =new String(fileName.getBytes("UTF-8"),"iso-8859-1");

        FileInputStream inputStream = null;
        OutputStream outputStream = null;

        File file = null;
        try {
            file = new File(task_log_path+"/"+data.getTask_log());
            if (!file.exists()) {

            } else {
                inputStream = new FileInputStream(file);
                response.setContentType("application/txt;charset=utf-8");
                response.setHeader("Content-Disposition",
                        "attachment;Filename=" + new String(downloadFileName.getBytes("GB2312"), "ISO8859-1"));// 設置下載後文件的名字、防止中文亂碼

                outputStream = response.getOutputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bytes)) > 0) {
                    outputStream.write(bytes, 0, len);
                }
            }
        } catch (IOException e) {

        } finally {
            try {
                if (inputStream != null) { inputStream.close(); }
                if (outputStream != null) { outputStream.close();}
            } catch (IOException e) {

            }
        }

//        // 直接下載String信息
//        OutputStream outputStream = null;
//        //將字符串轉化爲文件
//        byte[] currentLogByte = getById(task_id).getTask_log().getBytes();
//        try {
//            // 告訴瀏覽器用什麼軟件可以打開此文件
//            response.setHeader("content-Type","application/vnd.ms-excel");
//            // 下載文件的默認名稱
//            response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(downloadFileName,"utf-8"));
//
//            outputStream = response.getOutputStream();
//
//            outputStream.write(currentLogByte);
//
//        }catch (UnsupportedEncodingException e) {
//
//            e.printStackTrace();
//
//        }
    }

三、日誌文件的前端顯示獲取:

//通過id得到任務日誌
    @GetMapping("/getTaskLogById")
    String getTaskLogById(String task_id)
    {
        String taskLogInfo = "";
        AllTask_Log currentTaskLog=getById(task_id);
        String logSavePath = task_log_path+"/"+currentTaskLog.getTask_log();
        try {
            FileInputStream fileInputStream = new FileInputStream(logSavePath);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String line = null;
            while (true)
            {
                try {
                    if (!((line = bufferedReader.readLine())!=null)) {break;}
                    else {
                        taskLogInfo += line;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

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

        JSONObject json = new JSONObject(true);
        json.put("state",200);
        json.put("msg","success");
        json.put("data",taskLogInfo);
        return JSON.toJSONString(json, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章