相关疑难解决方法(0)

Spring Rest Web服务将文件作为资源返回

我正在尝试从服务器上部署的Rest Web服务返回文件流,并在客户端上从Rest Web服务处理此流.在服务器上我使用此代码:

@Override
@RequestMapping(value = "/file", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) 
public @ResponseBody Resource getAcquisition(@RequestParam(value="filePath", required = true) String filePath) throws FileNotFoundException{
    // acquiring the stream
    File file= new File(filePath);
    InputStream stream = new FileInputStream(file);
    // counting the length of data
    final long contentLength = file.length() ;

    return new InputStreamResource(stream){
        @Override
        public long contentLength() throws IOException {
            return contentLength;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

而且,此刻,在客户端我使用它(然后我必须在文件系统上写文件)

@Override
public void getFile(String serverIp, String toStorePath, String filePath) throws Exception{
    RestTemplate restTemplate = new …
Run Code Online (Sandbox Code Playgroud)

java rest spring file spring-mvc

6
推荐指数
1
解决办法
1万
查看次数

如何使用WebClient执行零拷贝上传和下载?

您可以使用Spring 5 WebFlux执行零拷贝上传和下载org.springframework.web.reactive.function.client.WebClient吗?

java spring-webflux

6
推荐指数
1
解决办法
2933
查看次数

响应后删除 tmp 文件吗?

我的用例:

  1. 根据用户请求创建tmp文件(我实际上不需要创建真实文件,但我需要有java.io.File实例)
  2. 处理这个文件
  3. 以 json 形式返回文件和其他元数据
  4. tmp永久删除文件

我的代码如下所示:

@GetMapping(produces = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MultiValueMap<String, Object>> regeneratePdfTest() throws IOException {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    File tempFile = File.createTempFile("temp-file-name", ".tmp");

    processFile(tempFile);

    parts.add("file", new HttpEntity<>(new FileSystemResource(tempFile)));
    parts.add("meta-data", new HttpEntity<>(someObject));

    return new ResponseEntity<>(parts, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

(这段代码最适合这种情况吗?)

我知道File.deleteOnExit(),但文档说

根据 Java 语言规范的定义,仅在虚拟机正常终止时才会尝试删除

就我而言,我想在响应后立即删除文件(文件有一些私人信息,我不想保留它们,也是安全内存,因为我不再需要这个文件)。

文件大小可能非常大(超过 200MB)。

更新 1: 如果发生错误我也想删除文件。

java spring-mvc spring-restcontroller

6
推荐指数
0
解决办法
4080
查看次数

从spring控制器下载文件会抛出IllegalStateException

我使用以下(这看起来很像这个)代码下载文件:

@RequestMapping(value = "/tunes/{file_name}", method = RequestMethod.GET)
public void downloadTune(@PathVariable(value = "file_name") String tuneId,
        HttpServletResponse response) {
    perfomanceLogger.trace("=== Start retrieving tune with id: " + tuneId);
    try {
        String location = "";
        // try {
        location = resourceManagementService.getArtifcatByIdAndType(tuneId,
                ControllerConstants.TYPE_MP3);
        String pathSeparator = File.separator;

        if (location == null || location.equals("")) {// load the default
                                                        // tune
            location = System.getProperties().get("jboss.server.base.dir")
                    + pathSeparator + ServicesConstants.FILE_LOCATION
                    + pathSeparator + "ringtone_1.mp3";
            if (!new File(location).exists()) {
                location = "";
            }
        }

        if (!location.equals("")) { …
Run Code Online (Sandbox Code Playgroud)

controller spring-mvc download spring-security illegalstateexception

5
推荐指数
1
解决办法
1146
查看次数

FileSystemResource 以内容类型 json 返回

我有以下返回文件的 spring mvc 方法:

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public FileSystemResource getFiles(@PathVariable String fileName){

    String path="/home/marios/Desktop/";

    return new FileSystemResource(path+fileName);

}
Run Code Online (Sandbox Code Playgroud)

我希望 ResourceHttpMessageConverter 根据其文档使用八位字节流类型创建适当的响应:

如果 JAF 不可用,则使用 application/octet-stream。

但是,尽管我正确地获取文件没有问题,但结果具有Content-Type: application/json;charset=UTF-8

你能告诉我为什么会这样吗?

(我使用 spring 版本 4.1.4。我没有明确设置任何消息转换器,我知道 spring 默认加载 ResourceHttpMessageConverter 和 MappingJackson2HttpMessageConverter,因为我的类路径中有 jackson 2,因为我有其他 mvc返回 json 的方法。

此外,如果我HttpEntity<FileSystemResource>手动使用和设置内容类型,或者用produces = MediaType.APPLICATION_OCTET_STREAM它指定它工作正常。

另请注意,在我的请求中,我没有指定任何接受内容类型,并且不希望依赖我的客户来做到这一点)

spring spring-mvc

5
推荐指数
1
解决办法
2294
查看次数

Java Spring - dynamically generated csv file download response is hanging

On my company's site we have some tables that we need to export to a csv file.
There are some varying parameters, so the csv file needs to be dynamically created on request.

My problem is that after clicking to download, the response hangs, and waits for the whole file to be created (which can take some time) and only then downloads the entire file in one instant.

I'm using AngularJS, so I'm using window.location = <url_for_file_download> In order to …

java csv spring opencsv

5
推荐指数
1
解决办法
2万
查看次数

使用Spring Boot和Thymeleaf创建文件下载链接

这可能听起来像一个微不足道的问题,但经过几个小时的搜索,我还没有找到答案.据我所知,问题是我试图FileSystemResource从控制器返回一个,而Thymeleaf希望我提供一个String资源,用它来渲染下一页.但是因为我回来了FileSystemResource,我得到以下错误:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "products/download", template might not exist or might not be accessible by any of the configured Template Resolvers
Run Code Online (Sandbox Code Playgroud)

我使用的控制器映射是:

@RequestMapping(value="/products/download", method=RequestMethod.GET)
public FileSystemResource downloadFile(@Param(value="id") Long id) {
    Product product = productRepo.findOne(id);
    return new FileSystemResource(new File(product.getFileUrl()));
}
Run Code Online (Sandbox Code Playgroud)

我的HTML链接看起来像这样:

<a th:href="${'products/download?id=' + product.id}"><span th:text="${product.name}"></span></a>
Run Code Online (Sandbox Code Playgroud)

我不希望被重定向到任何地方,我只需要在点击链接后下载文件.这实际上是正确的实现吗?我不确定.

java download thymeleaf spring-boot

4
推荐指数
2
解决办法
1万
查看次数

不在服务器响应中包含内容长度标头会产生什么后果?

RFC说,content-length头是可选的("..Applications应使用此字段...").

从我可以收集的内容中,如果不包括在内,那么客户端将不知道预期有多少数据,因此在下载正文时(即顶部栏而不是底部)将无法显示确定的进度条.

进展

省略此标题是否还有其他副作用或错误?

http httpresponse content-length http-headers

3
推荐指数
1
解决办法
5869
查看次数

在 Spring MVC 中使用 Java 从 Web Explorer 创建和下载 Excel

我想从 Java 中的方法创建一个 Excel 文件并将其下载到浏览器中。

我在这篇文章中找到了一个示例,您可以在其中创建 Excel 文件,但我想创建该.xls文件并从 Web 浏览器下载它。

我怎样才能做到这一点?

java excel spring-mvc

3
推荐指数
1
解决办法
5903
查看次数

如何使用 Undertow 返回要在 Java 中下载的文件?

我试图允许我的游戏客户端下载客户端运行所需的缓存。在我的游戏网络服务器内部我正在这样做:

@RouteManifest(template="/cache", method="GET")
public class APICacheRoute extends RouteHttpHandler<JadePreprocessor> {
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        Path path = Paths.get("./cache/Alterscape.zip");
        File file = path.toFile();
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");
        exchange.getResponseSender().send(file);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误消息,该文件必须是 ByteBuffer。如何返回文件以供下载?

我的网络服务器如下所示:

public static void initialize() {
    ServerController server = new ServerController("localhost", 8080, 8443);
    server.register(new APIVirtualHost());
    server.inititialize();
}
Run Code Online (Sandbox Code Playgroud)

我的 APIVirtualHost 如下所示:

public APIVirtualHost() {
    super(127.0.0.1);
    setDirectoryListingEnabled(false);
}
Run Code Online (Sandbox Code Playgroud)

java web undertow

3
推荐指数
1
解决办法
1713
查看次数

如何在AngularJS中读取Java属性文件?

有没有办法从位于Web服务器外部的angularjs读取属性文件?

就像在java中部署的属性文件一样,但我们可以在我们的项目中将这些文件作为filter.properties读取,这样任何解决方案都在angularJS中.

我试过这样但是未定义.

filter.properties:

key1=value1 
key2=value2
Run Code Online (Sandbox Code Playgroud)

sampleController.js

var app = angular.module('sampleApp', []);
    app.controller('sampleController', function($scope, $http) {
    $http.get('filter.properties').then(function (response) {
        console.log('a is ', JSON.stringify(response.data.key1));
    });
});
Run Code Online (Sandbox Code Playgroud)

javascript angularjs

2
推荐指数
1
解决办法
3257
查看次数