【问题标题】:Send file from Server to Client java with Spring and Rest web service使用 Spring 和 Rest Web 服务将文件从服务器发送到客户端 java
【发布时间】:2015-11-24 08:48:18
【问题描述】:

我必须通过 java 代码和 Rest web 服务将文件从服务器(从它的文件系统)发送到 Cliente(另一台电脑并将文件存储在一个特定的文件夹中)。这些文件甚至可以是 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[] 字符而不是原始文本

【问题讨论】:

  • 什么样的问题给你?一些错误......
  • 是的,我无法检索原始文件

标签: java spring file rest file-io


【解决方案1】:

据我了解,FileSystemResource 用于使用文件系统 URI 获取文件系统,但它不是通过 HTTP。使用 FileSystemResource,您可以从本地机器访问文件到本地可访问文件系统,以及从服务器访问文件到服务器可访问文件系统。但无法从本地访问服务器文件系统。

【讨论】:

  • 好的,我的问题是如何接收,例如我用其他方法更新上传文件
  • 从文件的服务器端字节数组发送并从客户端作为字节数组流接收并存储在客户端某处的字节数组流中
  • 喜欢上面的getAcquisition方法吗?
  • 我更新了主帖,但在客户端我如何将文件写入本地目录?
  • 使用 FileOutputStream .. 您可以在文件上写入字节数组,有很多示例可供参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 2018-06-18
  • 1970-01-01
  • 2015-05-02
  • 2013-10-30
  • 2011-04-04
相关资源
最近更新 更多