Java-based file upload and download

Recently, I made a small demo about file uploading and downloading. I encountered some small problems in the production, so I will record it here.

1. File upload

1. Front-end and corresponding back-end code:

<input name="upSource" type="file"/>
        private PrintWriter out = hresponse.getWriter();
    	//Determine whether the file exists (upSource is the file passed in from the foreground)
    	if(upSource!=null&&upSource.length()>0){
    		/ / Determine whether the incoming data format is the same as the selected format
    		String str=getThisType();//This is the file format type filled in by the front desk, the reader can remove it, and the value of the format here is obtained by matching the attributes of struts
    		String type=str.substring(str.lastIndexOf(".") + 1, str.length());//Get the file suffix
    	    //Convert the format to lowercase and compare it with the incoming format
    	    if(!model.getUform().toLowerCase().equals(type)){
    	    	out.print("<script language='javascript'>alert('The incoming file is in the same format as the selected file!'); history.back(0);</script>");
    		out.flush();
    		out.close();
    		return null;
    	    }
    	    String path = hrequest.getSession().getServletContext().getRealPath("/upload");//Get the upload path of the server file
    	    path=path+"\\"+model.getUname()+"."+model.getUform().toLowerCase();//Splicing the file name and suffix with the path (the model here matches the model of struts)
    	    try {
    	    	    FileInputStream fin = new FileInputStream(upSource);//Create a file input stream object			    	           
        	    FileOutputStream fout = new FileOutputStream(path);//Create a file output stream object (note that see title 3)
        	    int size= (int) upSource.length();
    	            byte [] buffer = new byte [size];
    		    while (fin.read(buffer) != -1 ) {
    		        fout.write(buffer);
                    }
    		    fout.flush();
    		    fout.close();
    		    fout = null;
    		    fin.close();
    		    fin = null;
            	    out.print("<script language='javascript'>alert('上传成功!'); history.back(0);</script>");
        	    out.flush();
        	    out.close();
        	    return null;
		} catch (Exception e) {
		     out.print("<script language='javascript'>alert('Upload failed, please upload again!'); history.back(0);</script>");
        	     out.flush();
        	     out.close();
        	     return null;
		}
    	}else{
    		out.print("<script language='javascript'>alert('The file you selected does not exist!'); history.back(0);</script>");
		out.flush();
		out.close();
		return null;
    	}

2. The effect diagram is as follows:


2. File download:

1. Background code

    	String uform=hrequest.getParameter("uname").
    	substring(hrequest.getParameter("uname").indexOf(".")+1, hrequest.getParameter("uname").length());
    	String uname=hrequest.getParameter("uname").substring(0,hrequest.getParameter("uname").indexOf("."));
    	String path = hrequest.getSession().getServletContext().getRealPath("/upload");//Get server resource storage file
    	String fileName=path+"\\"+hrequest.getParameter("uname").toLowerCase();//Get the full path of the file to be downloaded
	File file=new File(fileName);//Get the specified file
	if(!file.exists()){//Determine whether the file exists
	   out = hresponse.getWriter();
	   out.print("<script language='javascript'>alert('文件不存在!'); history.back(-1);</script>");
	   out.flush();
	   out.close();
	   return null;
	}
	else{
	   FileInputStream from=null;
	   ServletOutputStream oupstream=null;
	   from = new FileInputStream(file);//Get the input stream of the specified file
	   /* Set the file ContentType type, so setting will automatically determine the download file type*/
	   hresponse.setContentType("multipart/form-data");
	   hresponse.setContentType("application;charset=utf-8"); // Specify the save type of the file.
	   //solve the garbled problem
	   hresponse.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
	   fileName=file.getName();
	   try {
		oupstream = hresponse.getOutputStream();//Note here, see title 3
		int size=(int) file.length();
		byte[] buffer = new byte[size];
		int bytes_read;
		while ((bytes_read = from.read(buffer)) != -1) {
		    oupstream.write(buffer, 0, bytes_read);
		}
		oupstream.flush();
	        oupstream.close();
		// store download information
	    } catch (Exception e) {
		out = hresponse.getWriter();
		out.print("<script language='javascript'>alert('下载失败!'); history.back(-1);</script>");
		out.flush();
		out.close();
		return null;
	    }finally{
	        if(from != null){
		from.close();
		}
		if(oupstream != null){
		 oupstream = null;
		}
	    }
			
	  return null;
        }

2. The effect diagram is as follows:

  • Download list


  • download effect


Three points to note:

1. The <input type="file"> tag cannot correctly pass the path and name of the file into the background

After adding the <input type="file"> tag to the front page, you need to add the Enctype attribute to the form (Enctype is the encoding type used by the browser when sending data back to the server, and there are three encoding types).

Enctype has three parameters:

  • application/x-www-form-urlencoded: Encode all characters before sending (default). This is the standard encoding format. 
  • multipart/form-data: No character encoding, this value must be used when using a form that includes a file upload control. 
  • text/plain: The form data is encoded in plain text, without any controls or formatting characters. 
<form action="${ctx}/upload!upLoadSources.action" method="post" enctype="multipart/form-data" >

2. Two points to note when uploading files

  • The incoming path constructed in the output stream must contain the complete name and suffix of the path and the file, so that the data can be accurately written to the specified location after the output, otherwise an error will be reported.
  • In the uploaded file, if the file path or file name contains Chinese, in order to prevent the problem that the path cannot be found due to garbled characters, we need to process the full path through the following code.
path=new String(path.getBytes("iso-8859-1")."utf-8"));
3. The getOutputStream() method and the getWriter() method in resopnse are mutually exclusive, and one cannot use the other, so if you have to use getWriter(), you must write it in a module that is mutually exclusive with getOutputStream() For example, one is written in try and the other is written in catch.






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325853839&siteId=291194637