This article mainly introduces the code for downloading files and modifying file names in detail js, which has certain reference value. Interested friends can refer to it
js to download the file, use the tag and add the downloadattribute.
var a = document.createElement("a"); a.href = "XXX.com/audioStream/8a9dbae9d0859e48fc1f590fcf6d4ccc.mp3"; a.download ="test.mp3"; a.click();
But if you want to rename the file, it seems that js cannot do it.
So consider the background implementation, use java proxy to request, get the file setting file name, and return to the front end.
public void downFiles(HttpServletResponse response,String url,String workInfoId,int type){ try{ String prefix = type == 1 ? "wav" : "txt"; url = type == 1 ? url : (url + "?textInfoId="+workInfoId); HttpEntity entity = Request.Get(url). execute().returnResponse().getEntity(); byte[] bys = EntityUtils.toByteArray(entity); //获取作品名称 Works works = this.worksDao.findByWorkId(workInfoId); String name = (works!=null && StringUtils.isNotBlank(works.getName())) ? works.getName() : Long.toString(new Date().getTime()); response.setHeader("Content-Disposition", "attachment; filename="+ new String(name.getBytes("utf-8"), "ISO-8859-1")+"."+prefix); OutputStream out = response.getOutputStream(); out.write(bys); out.close(); }catch (Exception e){ e.printStackTrace(); } }
【Related recommendations】
1. Free js online video tutorial
2. JavaScript Chinese Reference Manual
3. php.cn Dugu Jiujian (3) - JavaScript video tutorial
The above is the detailed content of Example tutorial on downloading js and modifying file name. For more information, please follow other related articles on the PHP Chinese website!