fix: attachment upload to sm.ms failed. (#609)

* fix: attachment upload to sm.ms failed.

* fix: attachment upload to sm.ms failed.

* refactor: SmmsFileHandler.

* refactor: SmmsFileHandler.
pull/612/head
Ryan Wang 2020-03-02 13:04:53 +08:00 committed by GitHub
parent b23755a568
commit b70806960b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 5 deletions

View File

@ -17,6 +17,7 @@ import run.halo.app.exception.FileOperationException;
import run.halo.app.exception.ServiceException;
import run.halo.app.model.enums.AttachmentType;
import run.halo.app.model.properties.SmmsProperties;
import run.halo.app.model.support.HaloConst;
import run.halo.app.model.support.UploadResult;
import run.halo.app.service.OptionService;
import run.halo.app.utils.FilenameUtils;
@ -53,6 +54,8 @@ public class SmmsFileHandler implements FileHandler {
private final OptionService optionService;
private HttpHeaders headers = new HttpHeaders();
public SmmsFileHandler(RestTemplate httpsRestTemplate,
OptionService optionService) {
this.httpsRestTemplate = httpsRestTemplate;
@ -78,10 +81,9 @@ public class SmmsFileHandler implements FileHandler {
throw new FileOperationException("不支持的文件类型,仅支持 \"jpeg, jpg, png, gif, bmp\" 格式的图片");
}
HttpHeaders headers = new HttpHeaders();
setHeaders();
// Set content type
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.set(HttpHeaders.AUTHORIZATION, apiSecretToken);
LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
@ -114,7 +116,7 @@ public class SmmsFileHandler implements FileHandler {
throw new FileOperationException(smmsResponse == null ? "SM.MS 服务返回内容为空" : smmsResponse.getMessage()).setErrorData(smmsResponse);
}
if (smmsResponse.getSuccess()) {
if (!smmsResponse.getSuccess()) {
throw new FileOperationException("上传请求失败:" + smmsResponse.getMessage()).setErrorData(smmsResponse);
}
@ -146,8 +148,7 @@ public class SmmsFileHandler implements FileHandler {
// Build delete url
String url = String.format(DELETE_API_V2, key);
// Set user agent manually
HttpHeaders headers = new HttpHeaders();
setHeaders();
// Delete the file
ResponseEntity<String> responseEntity = httpsRestTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
@ -178,6 +179,14 @@ public class SmmsFileHandler implements FileHandler {
return smmsResponse != null && smmsResponse.getCode().equals(SUCCESS_CODE);
}
/**
* Set headers.
*/
private void setHeaders() {
headers.set(HttpHeaders.USER_AGENT, "Halo/" + HaloConst.HALO_VERSION);
headers.set(HttpHeaders.AUTHORIZATION, optionService.getByPropertyOfNonNull(SmmsProperties.SMMS_API_SECRET_TOKEN).toString());
}
@Data
@NoArgsConstructor
private static class SmmsResponse {