我必须通过java代码和Rest Web服务将文件从服务器(从其文件系统)发送到客户端(另一台电脑并将文件存储在特定文件夹中)。这些文件甚至可以120MB。
我使用 MultipartFile
从我的网页上传文件,但我不知道如何从客户端下载。
最好使用 REST Web 服务,该服务返回文件和消息以及方法结果(如果有错误,则为 true 或 false)。
你有好主意吗?
目前我在服务器中使用此代码:
最好的方法是
@Override
@RequestMapping(value = "/oldmethod", method = RequestMethod.GET)
public @ResponseBody Response getAcquisition(@RequestParam(value="path", defaultValue="/home") String path){
File file;
try {
file = matlabClientServices.getFile(path);
if (file.exists()){
InputStream inputStream = new FileInputStream(path);
byte[]out=org.apache.commons.io.IOUtils.toByteArray(inputStream);
return new Response(true, true, out, null);
}
else
return new Response(false, false, "File doesn't exist!", null);
} catch (Exception e) {
ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
LOG.error("Threw exception in MatlabClientControllerImpl::getAcquisition :" + errorResponse.getStacktrace());
return new Response(false, false, "Error during file retrieving!", errorResponse);
}
}
但是对于客户端来说,下面的代码不起作用:
public Response getFileTest(@RequestParam(value="path", defaultValue="/home") String path){
RestTemplate restTemplate = new RestTemplate();
Response response = restTemplate.getForObject("http://localhost:8086/ATS/client/file/oldmethod/?path={path}", Response.class, path);
if (response.isStatus() && response.isSuccess()){
try {
Files.write(Paths.get("PROVIAMOCI.txt"),org.apache.commons.io.IOUtils.toByteArray(response.getResult().toString()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return response;
}
它写入的是 byte[] 字符,而不是原始文本
最佳答案
根据我的理解,FileSystemResource 用于使用文件系统 URI 获取文件系统,但它不是通过 HTTP 进行的。使用 FileSystemResource,您可以从本地计算机到本地可访问文件系统以及从服务器到服务器可访问文件系统访问文件。但无法从本地访问服务器文件系统。
关于java - 使用 Spring 和 Rest Web 服务将文件从服务器发送到客户端 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33889062/