上傳作爲多部分表單/數據的文件(任何格式doc,docx,pdf,文本等)到Postman或應用程序UI的REST API。文本文件上傳正常。所有其他非文本格式被損壞。我無法打開這些文件。通過REST API多部分文件上傳損壞文件並增加文件大小
上傳文件的大小急劇增加。檢查下列服務器日誌:
File size just before call to request.getRequestDispatcher().forward(): 27583
Controller, first line in method:39439
上傳文件的大小爲27.3Kb
我猜的文件中獲取,因爲附加到文件中的其他數據的損壞。
控制器的方法是
@RequestMapping(value="/entity/{entity}/{entityId}/type/{type}/{derive}",method = RequestMethod.POST)
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile multipartFile,@PathVariable("entity")String entity,@PathVariable("type")String type,@PathVariable("entityId")Long entityId,@PathVariable("derive") boolean derive) throws Exception
由於文本文件保存正確和其他文件也得到正確書寫,不要以爲寫文件的代碼不正確。
代碼來獲得的inputStream
public String storeFile(MultipartFile multipartFile, String entity, Long id, String uploadType, boolean isDerive,String customName)
throws Exception
{
try
{
System.out.println(multipartFile.getSize());
String fileName = "";
String contentType = "";
if (multipartFile != null)
{
fileName = multipartFile.getOriginalFilename();
contentType = multipartFile.getContentType();
if (contentType == null)
{
contentType = "application/msword";
}
}
InputStream is = multipartFile.getInputStream();
String filePath = getFileName(entity, uploadType, id, fileName, isDerive,customName);
Helper.storeFile(is, filePath);
precedingPath = precedingPath.length() > 0 ? precedingPath + "/":"";
return precedingPath + filePath;
}
catch (WebException e)
{
e.printStackTrace();
throw e;
}
catch (Exception e)
{
e.printStackTrace();
throw new WebException(e.getMessage(), IHttpConstants.INTERNAL_SERVER_ERROR, e);
}
}
Helper.storeFile
public static File storeFile(InputStream is, String filePath) throws IOException {
try {
String staticRepoPath = null;
if (MasterData.getInstance().getSettingsMap().containsKey(Settings.REPO_LOCATION.toString())) {
staticRepoPath = MasterData.getInstance().getSettingsMap().get(Settings.REPO_LOCATION.toString());
} else {
throw new WebException("Invalid Settings");
}
byte[] buffer = new byte[is.available()];
is.read(buffer);
File targetFile = new File(staticRepoPath + File.separator + filePath);
@SuppressWarnings("resource")
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
return targetFile;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
我的Ajax請求如下:
var fd = new FormData();
//Take the first selected file
fd.append("file", document.actualFile);
//Generic AJAX call
CandidateService.ajax_uploadDocumentWithDocType($scope.candidate.id, fd, document.docType, function (error, json)
內容類型上載:
var config = {headers:{'X-Auth-Token':authToken, 'Content-Type': undefined}, transformRequest: angular.identity};
有誰知道我該如何解決這個問題併成功上傳文件?
Q1)爲什麼請求分派器和處理文件數據的控制器之間的文件大小發生了變化。 Q2)這個文件大小的改變是文件損壞的原因嗎?自由辦公室導致一般輸入/輸出錯誤。
不知道爲什麼有人標記-1。 我一直在使用這個API超過1年。自從最近3個月以來,文件在上傳時被破壞。通過git歷史徹底檢查了我的代碼。無法弄清楚改變了什麼。因此更深入地檢查文件大小等 API調用以上更新 – Sonal
您是否嘗試過使用其他API? –
我沒有downvote,但你沒有發佈代碼。沒辦法告訴你在用'MultipartFile'做什麼。 – chrylis