文件上传下载

2018-10-16  本文已影响0人  炼心之旅

文件上传下载,跟正常的Http请求,主要区分在Content-Type与Content-Disposition之处

文件上传,需要将ContentType指定为"multipart/form-data",服务端才能识别文件

 @RequestMapping(value="/upload/{fileType}", consumes="multipart/form-data", method=RequestMethod.POST)
 @ResponseBody
 public Boolean upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, @PathVariable String fileType) {
    return fileFacade.uploadFile(request, file, fileType);
}

    var formData = new FormData();
    formData.append('file', $('input[name=file]')[0].files[0]);
    $.ajax({
        url: url,
        method: 'POST',
        data: formData,
        contentType: false, // 注意这里应设为false
        processData: false,
        cache: false,
        success: function(data) {
            if(data) {
                searchList(1, 10);
            }
        },
        error: function (jqXHR) {
            console.log(JSON.stringify(jqXHR));
        }
    })

文件下载,需要将Content-Disposition指定为"Content-Disposition","attachment;filename=XXX",并返回byte数组,前端才能识别文件

/**
 * 下载文件
 * @param request
 * @param fileType
 * @return
 */
@RequestMapping(value="/download/{fileType}", method=RequestMethod.GET)
public ResponseEntity<byte[]> download(HttpServletRequest request, @PathVariable String fileType) {
    
    // c 获取文件资源
    GatewayFileData data = fileFacade.downloadFile(request, fileType);
    
    HttpHeaders headers=new HttpHeaders();//设置响应头
    headers.add("Content-Disposition", "attachment;filename="+data.getFileName());
    
    // c 返回文件响应
    ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(data.getFileContent(), headers, HttpStatus.OK);
    return response;
}
上一篇下一篇

猜你喜欢

热点阅读