[英]Convert outputstream byte array into string
我正在嘗試通過 DataOutputStream 將文件路徑發送到 Rest Api。 DataOutputStream 將字符串轉換為字節,我無法將字節轉換回所需的字符串。 這是我調用 Api 的方法
private void sendFilePath(String filePath) {
try {
URL url = new URL("http://localhost:8080/uploadExcelFile");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-
form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
DataOutputStream outputStream = new
DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(filePath);
outputStream.flush();
outputStream.close();
connection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
}
這是控制器方法又名 Api
@PostMapping("/uploadExcelFile")
public HttpStatus uploadFile(@RequestBody byte[] byteFilePath) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(byteFilePath);
String filePath = baos.toString();
Workbook workbook = WorkbookFactory.create(new File(filePath));
List<StudentModel> students = studentService.convertExcelToData(workbook);
return studentHandler.createStudent(students);
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
return HttpStatus.BAD_REQUEST;
}
}
sendFilePath() 中的文件路徑參數是D:\\Projects\\AutoFeeChallan\\Aptech Student Records.xlsx
而我在轉換為 String 后在 uploadApi 中得到的是D%3A%5CProjects%5CAutoFeeChallan%5CAptech+Student+Records.xlsx=
我希望控制器方法中的路徑與我在 sendFilePath() 中作為參數發送的路徑相同。 您能否提出解決此問題的任何解決方案或其他方法。
通過設置 ,
connection.setRequestProperty("Content-Type", "application/x-www-
form-urlencoded");
你對數據 URL 進行了編碼。在某些時候你需要對它進行 urldecode。
String filePath = java.net.URLDecoder.decode(baos.toString(), StandardCharsets.UTF_8);
或者您可以將內容類型更改為不同的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.