如何使用SpringMVC上传、显示、下载和删除文件
您好,我正在尝试使用spring mvc进行上传文件、显示文件、下载文件和删除文件等操作。我成功上传文件和删除文件。所有操作都运行良好,但接下来发生的事情是,当我上传上传的文件或图像时,显示或下载两次并获得 java.lang.IllegalStateException:已为此响应调用getOutputStream 选择文件1: 选择文件2: 文件名 形象 下载 删去如何使用SpringMVC上传、显示、下载和删除文件,spring,spring-mvc,Spring,Spring Mvc,您好,我正在尝试使用spring mvc进行上传文件、显示文件、下载文件和删除文件等操作。我成功上传文件和删除文件。所有操作都运行良好,但接下来发生的事情是,当我上传上传的文件或图像时,显示或下载两次并获得 java.lang.IllegalStateException:已为此响应调用getOutputStream 选择文件1: 选择文件2: 文件名 形象 下载 删去 如果我正确理解了你的问题,你可以这样做: public ResponseEntity<InputStreamResourc
如果我正确理解了你的问题,你可以这样做:
public ResponseEntity<InputStreamResource> getFile(@PathVariable("idForm") String idForm)
{
try
{
Student item = registerService.get(id);
HttpHeaders respHeaders = new HttpHeaders();
//Change it with your real content type
MediaType mediaType = new MediaType("img","jpg");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
//I suppose you have a method "getFileName"
//By using attachment you download the file; by using inline you should see the image in the browser
respHeaders.setContentDispositionFormData("attachment", item.getFileName());
InputStreamResource isr = new InputStreamResource(new ByteArrayOutputStream(item.getData()));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Error; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Angelo请看,我在尝试了更多内容后更新了我的问题。如果使用响应输出流,则无法返回新的模型和视图;o您返回null o您使用我发布的代码
public ResponseEntity<InputStreamResource> getFile(@PathVariable("idForm") String idForm)
{
try
{
Student item = registerService.get(id);
HttpHeaders respHeaders = new HttpHeaders();
//Change it with your real content type
MediaType mediaType = new MediaType("img","jpg");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
//I suppose you have a method "getFileName"
//By using attachment you download the file; by using inline you should see the image in the browser
respHeaders.setContentDispositionFormData("attachment", item.getFileName());
InputStreamResource isr = new InputStreamResource(new ByteArrayOutputStream(item.getData()));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Error; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}