ボタンをクリックして画像をダウンロード

2196 ワード

a便箋のリンクが指すactionはストリームを返す必要がある
@ApiOperation(value="    ",notes="")
	@RequestMapping(value="downPhoto",method=RequestMethod.GET)
	public void downPhoto(
			@RequestParam(value = "tid") Long tid,
			HttpServletRequest request,
			HttpServletResponse response
		) throws BusinessException{
		Photo photo = photoService.findPhoto(tid).getObject();
		photoService.updatePhotoDownNum(tid);
		String url = fileUploadPath+photo.getUrl();
		String ext = url.substring(url.lastIndexOf("."));
		//     
		Long filename = new Date().getTime();
		//               
		response.setContentType("APPLICATION/OCTET-STREAM"); 
		//               
		//response.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
		response.setHeader("Content-Disposition", "attachment;  filename=\""  +  filename+ext  +  "\"");
		try {
		//           
		OutputStream outputStream = response.getOutputStream();
		InputStream inputStream = new FileInputStream(url);
		byte[] buffer = new byte[1024];
		int i = -1;
		while ((i = inputStream.read(buffer)) != -1) {
		  outputStream.write(buffer, 0, i);
		}
		outputStream.flush();
		outputStream.close();
		
		inputStream.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

//jsコード
$("[name='downloadButton']").on("click",function(){
			var tid = $(this).attr("tid");
			var empId = $(this).attr("empId");
			if(userId == '' || !userId){
				alert("    !");
				window.location = basePath;
			}
	
			var url = basePath+"/m/photo/downPhoto?tid="+tid;
			//console.log(url);
                       //        ラベル、aラベルの に  が  です。 のラベルは     です。 えば、spanラベル、
//aだけならブラウザで  を くから
//  イベントをクリックするのは  のラベルでトリガーされ、イベントの を してaに され、ファイルを  ダウンロードすることができます
var aa = $("");
			$(this).parent().append(aa);
			aa.find("p").trigger("click");//           
			aa.remove();//  a  		
		})