spring mvc 下载附件处理

@Controller
public class DownLoadController {

    protected Log log = LogFactory.getLog(DownLoadController.class);
   
    @Autowired
    ResourceService resourceService;
   
    @Value("${image.directory}")
String imageServerDirectory;

    @RequestMapping(value = "/download/{resourceId}")
    public ResponseEntity<byte[]> download(@PathVariable Long resourceId) throws IOException { 
   
    Resource resource = resourceService.selectByPrimaryKey(resourceId);
    String downloadUrl = resource.getDownloadUrl();
    File sourceImageFile = new File(imageServerDirectory + downloadUrl);
   
        HttpHeaders headers = new HttpHeaders(); 
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
        //解决中文文件名下载没有名称问题
        headers.setContentDispositionFormData("attachment", new String(sourceImageFile.getName().getBytes("UTF-8"), "ISO8859-1")); 
  
        return new ResponseEntity<byte[]>(FileUtil.readAsByteArray(sourceImageFile), headers,
        HttpStatus.CREATED); 
    }
}

猜你喜欢

转载自kangcaiyuan.iteye.com/blog/2329568