上下文
我正在尝试创建一个宁静的API服务,该服务将允许上传文件并保存。该方法必须发布并作为字节[]发送。我也想创建一个RestTemplate客户端来发送文件。
问题
已创建文件,但尚未上传,因为它占用1 KB。我不知道问题出在哪里。也许restTemplate没有发送字节[]。
代码
Restful Api服务
服务
@Service
public class FileSaveService {
@Value("${path.file}")
private String path;
@Value("${filename}")
private String name;
public void save(byte[] bytes) {
try {
FileUtils.writeByteArrayToFile(new File(path + name), bytes);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path + name)));
stream.write(bytes);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推车
@RestController
@RequestMapping("v1/")
public class FileSaveController {
@Autowired
private FileSaveService fileSave;
@RequestMapping(value = "sent", method = RequestMethod.POST)
public String getFile(@RequestParam byte[] data) {
fileSave.save(data);
return "Ok";
}
}
RestTemplate客户端:
@Service
public class FileSentService {
final static private String URL = "http://localhost:8080/v1/sent";
private RestTemplate restTemplate = new RestTemplate();
public String convertFileToByteArr() throws IOException {
InputStream in = new ClassPathResource("pdf.pdf").getInputStream();
URI url = UriComponentsBuilder.fromHttpUrl(URL).queryParam("data", IOUtils.toByteArray( in )).build().encode()
.toUri();
return restTemplate.postForObject(url, null, String.class);
}
}
控制器
@RestController
public class FileSent {
@Autowired
private FileSentService fileSent;
@RequestMapping(method = RequestMethod.POST, value = "upload")
public byte[] sent() {
try {
return fileSent.convertFileToByteArr();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
答案 0 :(得分:0)
您可以使用@RequestBody
标签将字节放入请求正文