File download browser opens files directly instead of saving related issues

Source: Internet
Author: User
Tags file upload json

yesterday did springmvc file upload download function encountered a lot of problems. One of the problems is that the TXT CSS JS HTML XML PDF and so on when the file download browser (HTML5 's a tag download property is not supported by all browsers) is opened directly, rather than download save. There are a lot of ways to solve this online, and I'm just integrating here and being a mark.

Scene is a URL, the boss reminds me to use the background access to the URL to get file flow foreground to handle. Probably this process code is as follows:

Front-end JS section, reference

Get the stitching string
function getfjinfo (name, URL) {
	return ' <tr><td style= ' ><a  href= ' javascript: void (0) ' onclick= ' Getdownfile (\ "" + URL + "\", \ "" + name + "\") ' > "+ name +" </a></td></tr> "
  //File Download
function getdownfile (URL, name) {
	var param = {
		"url": URL
	$.ajax ({
		url:contextpath + '/product-label/file2stream ',
		type: ' GET ',
		data:Base64.encode ( Json.encode (param)),
		dataType: "Text",
		success:function (data) {
			downloadFile (name, data)
Stream processing triggers the Download event
function downloadFile (fileName, content) {
	var aLink = document.createelement (' a ');
	var blob = new blob ([content]);
	var evt = document.createevent ("mouseevents");
	Evt.initmouseevent ("Click", True, false, window, 0, 0, 0, 0, 0, False, False, False, FALSE, 0, null); = FileName;
	Alink.href = Url.createobjecturl (BLOB);
	Alink.dispatchevent (evt)

Background controller processing, reference

/** * Returns the stream * * @param requestmap Request parameter * @param response returns the object */@RequestMapping (value = "/fil E2stream ", method = requestmethod.get) public void File2stream (@Json map<string, object> Requestmap, HttpServlet
            Response Response) {try {String url = string.valueof (requestmap.get ("url"));
            url url =new url (string.valueof (requestmap.get ("url"));
            InputStream iStream = getfilestream (URL);
            OutputStream stream = Response.getoutputstream ();
            Stream.Write (Streamutils.getbytes (IStream));
            Stream.flush ();
        Stream.Close (); } catch (Exception e) {log.error ("Productsalesrecommendcontroller.file2stream error |
        ({}) ", E);  }}/** * HttpURLConnection get the file stream of the network path * * @param URL link * @return InputStream * @throws IOException */private inputstream getfilestream (url url) throws IOException {HttpurlconNection conn = (httpurlconnection) url.openconnection ();
        Conn.setconnecttimeout (5 * 1000);
        Conn.setrequestmethod ("GET");
        InputStream instream = Conn.getinputstream ();
    return instream; }/** * HttpClient get the file stream of the network path * * @param URL link String * @return InputStream * @throws illegalst Ateexception * @throws IOException */Private InputStream getfilestream (String url) throws Illegalstateexcep
        tion, IOException {httpparams httpparams = new Basichttpparams (); Httpconnectionparams.setconnectiontimeout (Httpparams, 5000); Set the connection timeout to 5 seconds HttpClient client = new Defaulthttpclient (httpparams); Generate an HTTP client send Request object HttpResponse HttpResponse = Client.execute (new HttpGet (URL)); Send the request and wait for the response httpentity entity = httpresponse.getentity ();
        Get the content inside the response InputStream instream = Entity.getcontent ();
    return instream; }

Let's do it first. The boss says there's more on the big one. Let's see it sometime.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.