Home > Web Front-end > JS Tutorial > body text

Example tutorial on downloading js and modifying file name

零下一度
Release: 2017-05-10 11:06:45
Original
2991 people have browsed it

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();
Copy after login

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();
    }

  }
Copy after login

【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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!