Bug fixes file upload and download

This commit is contained in:
2020-04-11 22:47:54 +02:00
parent 91cbe58e09
commit c5c601cffe
5 changed files with 30 additions and 3 deletions

View File

@@ -5,6 +5,8 @@ import de.financer.model.File;
import de.financer.template.FinancerRestTemplate;
import de.financer.template.exception.FinancerRestException;
import de.financer.util.ControllerUtils;
import org.overviewproject.mime_types.GetBytesException;
import org.overviewproject.mime_types.MimeTypeDetector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
@@ -36,8 +38,20 @@ public class FileController {
return null;
}
final byte[] decodedFileContent = Base64.getDecoder().decode(file.getContent());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
.body(new ByteArrayResource(Base64.getDecoder().decode(file.getContent())));
.header(HttpHeaders.CONTENT_TYPE, getMimeTypeForFile(file.getName(), decodedFileContent))
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(decodedFileContent.length))
.body(new ByteArrayResource(decodedFileContent));
}
private String getMimeTypeForFile(String fileName, byte[] content) {
try {
return new MimeTypeDetector().detectMimeType(fileName, () -> content);
} catch(GetBytesException e) {
return "text/html";
}
}
}

View File

@@ -11,6 +11,7 @@ import de.financer.form.NewTransactionForm;
import de.financer.model.Account;
import de.financer.template.exception.FinancerRestException;
import de.financer.util.ControllerUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Controller;
@@ -119,7 +120,7 @@ public class TransactionController {
requestDto.setDescription(form.getDescription());
requestDto.setTaxRelevant(form.getTaxRelevant());
if (form.getFile() != null) {
if (form.getFile() != null && StringUtils.isNotEmpty(form.getFile().getOriginalFilename())) {
try {
requestDto.setFileContent(Base64.getEncoder().encodeToString(form.getFile().getBytes()));
requestDto.setFileName(form.getFile().getOriginalFilename());

View File

@@ -1,3 +1,7 @@
v29 -> v30:
- Fix a bug in the file upload feature that caused every transaction to have a file, even though no file was uploaded
- Set proper HTTP headers for file download (mime type, length)
v28 -> v29:
- Internal optimizations