如何使用spring mvc上传,显示,下载和删除文件

时间:2017-03-01 07:40:04

标签: spring spring-mvc

我正在尝试上传文件,显示文件,下载文件和使用spring mvc删除文件等操作我成功上传文件并删除文件所有操作都运行正常但后来发生的事情是我上传的时候上传的文件或图像显示或下载两次并获取 java.lang.IllegalStateException:已为此响应调用了getOutputStream()

    <form method="post" action="doUpload" enctype="multipart/form-data">
       <table border="0">
           <tr>
               <td>Pick file #1:</td>
                <td><input type="file" name="fileUpload" size="50" /></td>
             </tr>
       <tr>
                        <td>Pick file #2:</td>
                        <td><input type="file" name="fileUpload" size="50" /></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center"><input type="submit" value="Upload" /></td>
                    </tr>
                </table>
            </form>

<table border="1" bgcolor="black" width="600px">
<tr style="background-color: teal; color: white; text-align: center;"
        height="40px">
<td>File Name</td>
<td>Image</td>
<td>Download</td>
<td>Delete</td>
</tr>
    <c:forEach items="${employeeList}" var="user">
      <tr style="background-color: white; color: black; text-align: center;"
                                                height="30px">
            <td><c:out value="${user.fileName}" /></td>
            <td><img src="show?id=${user.id}" /></td>
            <td><a href="edit?id=${user.id}">Download</a></td>
            <td><a href="delete?id=${user.id}">Delete</a></td>
        </tr>
    </c:forEach>
</table>
    @Controller
@RequestMapping("/")
public class RegistrationController {
    @Autowired
    private IRegistrationService registerService;

    @RequestMapping(value = "/saveParentAndStudentFromAdmin", method = RequestMethod.POST)
    public ModelAndView saveParentAndStudentByAdmin(
            @ModelAttribute Student student,
            @RequestParam CommonsMultipartFile[] fileUpload) {
        if (fileUpload != null && fileUpload.length > 0) {
            for (CommonsMultipartFile aFile : fileUpload) {
                System.out.println("Saving file: "
                        + aFile.getOriginalFilename());
                student.setFileName(aFile.getOriginalFilename());
                student.setFileType(aFile.getContentType());
                student.setData(aFile.getBytes());
                registerService.saveParentAndStudentByAdmin(student);
            }
        }
        java.util.List<Student> uploadedFiles = registerService.findAllFiles();
        return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
                uploadedFiles);

    }

    @RequestMapping("delete")
    public ModelAndView deleteUser(@RequestParam int id) {
        registerService.deleteRow(id);
        java.util.List<Student> uploadedFiles = registerService.findAllFiles();
        return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
                uploadedFiles);

    }

    @RequestMapping("show")
    public ModelAndView displayImage(@RequestParam int id,
            HttpServletResponse response, HttpServletRequest request) {

        System.out.println("Id to display image: " + id);
        Student item = registerService.get(id);
        response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
        try {
            response.getOutputStream().write(item.getData());

        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            response.getOutputStream().close();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return new ModelAndView("StudentEnrollmentFromAdmin");
    }

    @RequestMapping("downalod")
    public ModelAndView downloadFile(@RequestParam int id,
            HttpServletResponse response, HttpServletRequest request) {

        System.out.println("Id to download: " + id);

        Student student = registerService.get(id);
        response.setContentType(student.getFileType());
        response.setContentLength(student.getData().length);
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + student.getFileName() + "\"");

        try {
            FileCopyUtils.copy(student.getData(), response.getOutputStream());
        } catch (IOException e) {

            e.printStackTrace();
        }
        java.util.List<Student> uploadedFiles = registerService.findAllFiles();
        return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
                uploadedFiles);
    }
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解了你的问题,你可以这样做:

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

安吉洛