使用RestTemplate上传MultipartFiles

时间:2019-10-11 15:05:20

标签: spring-boot resttemplate

我有两个终点。一个端点将从Postman接收文件,并应使用RestTemplate将相同文件转发到另一个端点。

第二个端点正在被调用,但没有文件。

端点1:

@PostMapping("/upload/test")
    public String testUpload(@RequestParam("files") List<MultipartFile> files) throws IOException{

        if (files.isEmpty()) {          
            return "Please select a file . . .";
        }
        System.out.println("**** Number of files : "+files.size());



        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        List<Object> f = new ArrayList<>();
        for(MultipartFile file : files) {
            f.add(new ByteArrayResource(file.getBytes()));
        }
        map.put("files", f);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8085/upload/test/client",
                HttpMethod.POST, requestEntity, String.class);
        System.out.println("response status: " + response.getStatusCode());
        System.out.println("response body: " + response.getBody());


        return "success";
    }

端点2:

@PostMapping("/upload/test/client")
    public String testClient(@RequestParam("files") List<MultipartFile> files){
        System.out.println("********inside client  *****************");
        System.out.println(files);
        return "200";
    }

O / P:

**** Number of files : 2
********inside client  *****************
[]
response status: 200 OK
response body: 200

2 个答案:

答案 0 :(得分:1)

我解决了以下问题,并且也适用于多个文件。

端点1

    @PostMapping("/upload")
    public ResponseEntity testUpload(@RequestParam("file") List<MultipartFile> file) throws IOException{
        System.out.println("********received file:"+file.size());
        String serverUrl = "http://localhost:8080/upload/client";

        MultiValueMap<String, Object> body =getMultivalueMap(file);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity= new HttpEntity<>(body, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
        System.out.println(response);

        return new ResponseEntity<>(HttpStatus.OK);
    }

端点2

   @PostMapping("/upload/client")
    public ResponseEntity testClient(@RequestParam("file") List<MultipartFile> file){

        System.out.println("********client file:"+file.size());
        file.forEach(f->{
            System.out.println("### Client File Name :"+f.getOriginalFilename());           
        });
        return new ResponseEntity<>(HttpStatus.OK);
    }

正文内容

private MultiValueMap<String, Object> getMultivalueMap(List<MultipartFile> files) throws IOException {
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        for(MultipartFile file : files) {
            ByteArrayResource contentsAsResource = new ByteArrayResource(file.getBytes()){
                @Override
                public String getFilename(){
                    return file.getOriginalFilename();
                }
            };
            map.add("file", contentsAsResource);
        }
        return map;
    }

答案 1 :(得分:0)

据了解,您可以使用$city = (isset($_GET['city'])) ? $_GET['city'] : 0; $suburb = (isset($_GET['suburb'])) ? $_GET['suburb'] : 0; $minBed = (isset($_GET['minBed'])) ? $_GET['minBed'] : 0; $maxBed = (isset($_GET['maxBed'])) ? $_GET['maxBed'] : 0; $minBath = (isset($_GET['minBath'])) ? $_GET['minBath'] : 0; $maxBath = (isset($_GET['maxBath'])) ? $_GET['maxBath'] : 0; $minPrice = (isset($_GET['minPrice'])) ? $_GET['minPrice'] : 0; $maxPrice = (isset($_GET['maxPrice'])) ? $_GET['maxPrice'] : 0; $pagingVariable = ''; $cityName =''; //} $rowsPerPage = 8; // edit the number of rows per page $query = "SELECT tbl_property.property_ID, tbl_property.name, tbl_property.location, tbl_property.description, tbl_property. price, tbl_property.landsize, tbl_property.property_image, tbl_property.bedrooms, tbl_property.bathrooms, tbl_property.garage, tbl_agents.agent_name, tbl_agents.agent_image, tbl_city.cityName FROM tbl_property INNER JOIN tbl_agents ON tbl_property.agent_ID=tbl_agents.agent_ID INNER JOIN tbl_city ON tbl_property.city_ID=tbl_city.city_ID"; //$query = "SELECT tbl_property.property_ID, tbl_property.name, tbl_property.location, tbl_property.description, tbl_property. price, tbl_property.landsize, tbl_property.property_image, tbl_property.bedrooms, tbl_property.bathrooms, tbl_property.garage, tbl_agents.agent_name, tbl_agents.agent_image FROM tbl_property INNER JOIN tbl_agents ON tbl_property.agent_ID=tbl_agents.agent_ID"; $pagingLink = getPagingLink($query, $rowsPerPage); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); if($city == 0){ $query .= " WHERE "; } if($city != 0){ $query = "SELECT tbl_property.property_ID, tbl_property.name, tbl_property.location, tbl_property.description, tbl_property.price, tbl_property.landsize, tbl_property.property_image, tbl_property.bedrooms, tbl_property.bathrooms, tbl_property.garage, tbl_agents.agent_name, tbl_agents.agent_image, tbl_city.cityName FROM tbl_property INNER JOIN tbl_agents ON tbl_property.agent_ID=tbl_agents.agent_ID INNER JOIN tbl_city ON tbl_property.city_ID=tbl_city.city_ID WHERE tbl_property.city_ID ='$city'"; $pagingVariable .= "&city=".$_GET['city']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($suburb != 0){ $query .= "AND suburb_ID ='$suburb'"; $pagingVariable .= "&suburb=".$_GET['suburb']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minBed != 0 && $maxBed == 0 && $city == 0){ $query .= " bedrooms >='$minBed'"; $pagingVariable .= "&minBed=".$_GET['minBed']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minBed != 0 && $city != 0){ $query .= "AND bedrooms >='$minBed'"; $pagingVariable .= "&minBed=".$_GET['minBed']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($maxBed != 0 && $minBed == 0 && $city == 0){ $query .= " bedrooms <='$maxBed'"; $pagingVariable .= "&maxBed=".$_GET['maxBed']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($maxBed != 0 && $minBed == 0 && $city != 0){ $query .= "AND bedrooms <='$maxBed'"; $pagingVariable .= "&maxBed=".$_GET['maxBed']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minBed != 0 && $maxBed != 0 && $city != 0){ $query .= "AND (bedrooms BETWEEN '$minBed' AND '$maxBed')"; $pagingVariable .= "&minBed=".$_GET['minBed']."&maxBed=".$_GET['maxBed']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minBed != 0 && $maxBed != 0 && $city == 0){ $query .= " (bedrooms BETWEEN '$minBed' AND '$maxBed')"; $pagingVariable .= "&minBed=".$_GET['minBed']."&maxBed=".$_GET['maxBed']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if ( ((($minBed != 0 || $maxBed != 0) && $city != 0)) || ((($minBed != 0 || $maxBed != 0) && $city == 0)) || ((($minBed == 0 && $maxBed == 0) && $city != 0))){ $query .= " AND"; } if($minBath != 0 && $maxBath == 0 && $city == 0){ $query .= " bathrooms >='$minBath'"; $pagingVariable .= "&minBath=".$_GET['minBath']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minBath != 0 && $maxBath == 0 && $city != 0){ $query .= " bathrooms >='$minBath'"; $pagingVariable .= "&minBath=".$_GET['minBath']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minBath != 0 && $maxBath != 0 && $city == 0){ $query .= " (bathrooms BETWEEN '$minBath' AND '$maxBath')"; $pagingVariable .= "&minBath=".$_GET['minBath']."&maxBath=".$_GET['maxBath']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minBath != 0 && $maxBath != 0 && $city != 0){ $query .= " (bathrooms BETWEEN '$minBath' AND '$maxBath')"; $pagingVariable .= "&minBath=".$_GET['minBath']."&maxBath=".$_GET['maxBath']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($maxBath != 0 && $minBath == 0 && $city == 0){ $query .= " bathrooms <='$maxBath'"; $pagingVariable .= "&maxBath=".$_GET['maxBath']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($maxBath != 0 && $minBath == 0 && $city != 0){ $query .= " bathrooms <='$maxBath'"; $pagingVariable .= "&maxBath=".$_GET['maxBath']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } // // if ($minBath != 0 || $maxBath != 0){ $query .= " AND"; } if($minPrice != 0 && $maxPrice == 0 && $city == 0){ $query .= " Price >='$minPrice'"; $pagingVariable .= "&minPrice=".$_GET['minPrice']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minPrice != 0 && $maxPrice == 0 && $city != 0){ $query .= " Price >='$minPrice'"; $pagingVariable .= "&minPrice=".$_GET['minPrice']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minPrice != 0 && $maxPrice != 0 && $city == 0){ $query .= " (Price BETWEEN '$minPrice' AND '$maxPrice')"; $pagingVariable .= "&minPrice=".$_GET['minPrice']."&maxPrice=".$_GET['maxPrice']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($minPrice != 0 && $maxPrice != 0 && $city != 0){ $query .= " (Price BETWEEN '$minPrice' AND '$maxPrice')"; $pagingVariable .= "&minPrice=".$_GET['minPrice']."&maxPrice=".$_GET['maxPrice']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($maxPrice != 0 && $minPrice == 0 && $city == 0){ $query .= " Price <='$maxPrice'"; $pagingVariable .= "&maxPrice=".$_GET['maxPrice']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if($maxPrice != 0 && $minPrice == 0 && $city != 0){ $query .= " Price <='$maxPrice'"; $pagingVariable .= "&maxPrice=".$_GET['maxPrice']; $pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable); $result = mysqli_query($link, getPagingQuery($query, $rowsPerPage)); } if (mysqli_num_rows($result) < 1) { $noResults = "Sorry, no results were found!"; } else { while($row = mysqli_fetch_array($result)) { extract($row); ?> <div class="col-md-6"> <div class="propertyCardOuter card"> <a href="addWishList.php?propertyID=<?php echo $row['property_ID']; ?>"><div title="add to watchlist" class="displayWishAdd"><div class="plusSymbol"><?php echo $OnWishList;?></div></div></a> <a class="propertyCardLink" href="viewProperty.php?propertyID=<?php echo $row['property_ID']; ?>"><div class="card propertyCard"> <div class="propertyImgContainer"> <img alt="Photo" class="PropertyImagesHome img-fluid" src="<?php echo 'property-images/'.$row['property_image']; ?>" title="<?php echo $row['name']; ?>" /> </div> <div class="row"> <div class="col-md-9 propertyInfoBox"> <div class="propertyName"> <?php echo $row['name']; ?></div> <div style="font-size: 14px;"> <?php echo $row['location']; ?> </div> <hr> <div class="houseDetails"> <?php echo $row['bedrooms']; ?> <i class="fa fa-bed icons"></i><?php echo $row['bathrooms']; ?> <i class="fa fa-bath icons"></i><?php echo $row['garage']; ?> <i class="fa fa-car icons"></i><?php echo $row['landsize'] . 'sqm'; ?> <img src="images/landSizeIcon.png" width="19px;" alt="landsize"/> <span class="propertyPrice"><?php echo '$' . number_format($row['price']); ?></span> </div> </div> <div class=" col-sm-12 col-md-3"> <div class="agentContainer"> <div class="agentPhotoContainer"> <img alt="Photo" class="agentImage" src="<?php echo 'property-images/'.$row['agent_image']; ?>" title="photo" /> </div> <div style="text-align:center; margin-top: 10px;"><?php echo $row['agent_name']; ?></div></div> </div> </div> </div></a></div> <h3 style="text-align:right;"> </h3> </div> <?php $propertyID2 = $row['property_ID']; $query2 = "SELECT * FROM tbl_wishlist WHERE member_ID='$memberID' && property_wishList_ID='$propertyID2' "; $result2 = mysqli_query($link, $query2); // execute the SQL if ($row = mysqli_fetch_array($result2)) { $OnWishList = "<span id='tickSpan'>&#10003;</span>"; } else { $OnWishList = "<span id='plusSpan'>+</span>"; } } } // end of while loop } ?> 创建一个临时文件,并在使用File f=File.createTempFile()成功交易后将其删除。

f.deleteOnExit()

我没有尝试将文件转发到另一个端点,但是成功完成了字符串操作。希望上述方法必须有助于克服该问题。有关文件Java doc

的更多信息