简体   繁体   中英

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

I have to send file from Server (from its file system) to Cliente (another pc and store file in a particularly folder) through java code and Rest web service. These files can be even 120MB . I used MultipartFile to upload file from my web page but I don't know how to download from the client. It would be good the possibility to use a REST web service that returns both file and message with result of method (true or false if there was an error). Do you have an idea? At the moment I use this code in server:

and the best way would be

@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);
    }       
}

but to the client the code below doesn't work:

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;
    }

it writes the byte[] characters and not the original text

As per my understanding FileSystemResource used for get the file system using file system URI but it is not over the HTTP. Using FileSystemResource you can access files from your local machine to local accessible file system and from server to your server accesiable file system. But could not access from local to server file system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM