簡體   English   中英

使用Spring和Rest Web服務將文件從服務器發送到Client Java

[英]Send file from Server to Client java with Spring and Rest web service

我必須通過Java代碼和Rest Web服務將服務器中的文件(從其文件系統)發送到Cliente(另一台PC並將文件存儲在特定的文件夾中)。 這些文件甚至可以是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,您可以將文件從本地計算機訪問到本地可訪問文件系統,也可以從服務器訪問服務器可訪問的文件系統。 但是無法從本地訪問服務器文件系統。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM