上傳文件並轉爲json對象Demo(不需要存服務器)

不需要存服務器,因爲存服務器會有多實例的問題,這次上傳到服務器的A節點,下次請求到B節點會存在訪問不到文件的問題,所以需要每次上傳文件進行解析。
@ApiOperation("解析配置文件")
@PostMapping("/resolveProfile")
public Response resolveProfile(@RequestParam @ControllerLog(paramName = "配置文件", entityType = ConstLog.OPER_LOG_NAME_BY_ID.SOFTWARE) MultipartFile profile) {
    if (profile.isEmpty()) {
        return Response.fail(-1, "請檢查文件內容");
    }
    try {
        Reader reader = new InputStreamReader(profile.getInputStream(), "utf-8");
        BufferedReader bReader = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String temp;
        String resultString;
        while ((temp = bReader.readLine()) != null) {//逐行讀取文件內容
            sb.append(temp);
        }
        bReader.close();
        resultString = sb.toString();
        PatchAcceptDTO patchAcceptDTO = JSON.parseObject(resultString, PatchAcceptDTO.class);
        if (patchAcceptDTO.getPatchConfig().size() != patchAcceptDTO.getPatchTypeConfig().size()) {
            return Response.fail(-1, "補丁類型和補丁詳情個數不匹配,請檢查文件內容");
        }
        //hasCheck  1-已校驗,2-未校驗
        if (patchAcceptDTO.getHasCheck() == 1) {
            return Response.success("解析配置文件成功");
        } else {
            return Response.fail(-1, "未運行工具進行本地校驗,請檢查文件內容");
        }
    } catch (Exception e) {
        logger.info("解析配置文件錯誤", e);
        return Response.fail(-1, "解析配置文件錯誤");
    }
}
import org.apache.commons.io.IOUtils;

其實IOUtils這個包已經封裝了原生的讀取方法,所以可以用一行代碼代替

String content = IOUtils.toString(profile.getInputStream(), "utf-8");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章