Jersey RESTful WebService框架学习(八)文件下载防乱码
程序员文章站
2022-06-12 11:00:55
...
最近在做下载时候 不同浏览器下载的文件一直出现乱码,不知道怎么设置文件的编码,百度许久,找到一个解决办法如下
设置header("Content-disposition","attachment;filename=" + nFileName+";filename*=utf-8''"+nFileName)即可
/** * 文件下载 * @param request * @return */ @GET @Path("/d") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response download(@QueryParam("filemd5") String viFileMd5,@QueryParam("filename") String viFileName,@Context HttpServletResponse response) { File nFile = new File(WebConfig.MAIN_UPLOAD_TEMP_PATH + File.separator+ viFileMd5); // 如果文件不存在,提示404 if (!nFile.exists()) { return Response.status(Response.Status.NOT_FOUND).build(); } String nFileName = null; try { nFileName = URLEncoder.encode(viFileName, "UTF-8"); response.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } return Response.ok(nFile).header("Content-disposition","attachment;filename=" + nFileName+";filename*=utf-8''"+nFileName).header("Cache-Control", "no-cache").build(); }
设置header("Content-disposition","attachment;filename=" + nFileName+";filename*=utf-8''"+nFileName)即可