This article shares the specific code for Java to implement file upload and download function for your reference. The specific content is as follows
The front-end uses the enctype property of the form form to modify the data delivery method to the binary "stream" form. The server (servlet) obtains the flow information through getInputStream(), and uses the basic operations of the java I/O stream to write the flow to a file temp temporarily created by the server. Then, use the basic file operations again to read and intercept the content of the temporary file, create the corresponding file based on the information in it, and write the specific information read out. When downloading, find the corresponding file on the server based on the submitted file name, and then output it to the page according to the output stream outStream, and set the response type and response header of the servlet.
The specific transmission process is as follows:
The part of the flow information is:
The specific code is as follows:
Front-end code:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><script src="Js/jquery.js"></script></head><body> <form action="FileUpServlet" method="post" enctype="multipart/form-data"> <table> <tr> <td>Please select upload file:</td><td><input id="myfile" name="myfile" type="file" value="" /></td> <td><input type="submit" value="upload"></td> </tr> <tr><td>${info}</td></tr> </table> </form> File download: <a href="FileLoadownServlet?filename=${filename}">${filename}</a></body></html>Upload servlet part (core)
@WebServlet("/FileUpServlet")public class FileUpServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FileUpServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); InputStream filesource = request.getInputStream();//request gets stream information String tempname = "D:/temp";//tempfile represents temporary storage of files File tempfile = new File(tempname);//create temporary file FileOutputStream outputStream = new FileOutputStream(tempfile);//Output stream object, specifying the output refers to the tempfile directory byte b[] = new byte[1024]; int n; while((n = filesource.read(b))!= -1)//Read 1024 bytes from the output stream each time until you finish reading { outputStream.write(b,0,n); } outputStream.close(); filesource.close();//Close the input and output stream/*The following are specific file operations, mainly for parsing temporary generated temp files, and most of the knowledge is the content of the java input and output stream! */ RandomAccessFile randomfile = new RandomAccessFile(tempfile, "r");//Random stream, specify to read temporary files, read only randomfile.readLine();//Read the first line, invalid data, no String str = randomfile.readLine();//Read the second line int beginIndex = str.lastIndexOf("=")+2;//Specify the starting position of the required data int endIndex = str.lastIndexOf("/"");//Specify the location of the required data String filename = str.substring(beginIndex,endIndex);//Intercept the file name//Reposition the file pointer and get the file content randomfile.seek(0);//File pointer starts from the beginning long startext = 0; int i = 1; //File content starts while((n=randomfile.readByte()) != -1&&i <= 4) { if(n=='/n') { startext = randomfile.getFilePointer(); i++; } } startext = randomfile.getFilePointer() - 1; //File content ends randomfile.seek(randomfile.length()); long endtext = randomfile.getFilePointer(); int j = 1; while(endtext >= 0 && j <= 2) { endtext--; randomfile.seek(endtext); if(randomfile.readByte()=='/n') { j++; } } endtext = endtext-1; //Save the temporary file to the specified directory String realpath = getServletContext().getRealPath("/")+"images";//Set the file saving directory System.out.println(realpath); File fileupload = new File(realpath); if(!fileupload.exists()) { fileupload.mkdir();//Create if the directory does not exist} File savefile = new File(realpath,filename); RandomAccessFile randomAccessFile = new RandomAccessFile(savefile, "rw"); randomfile.seek(startext); while(startext<endtext){ randomAccessFile.write(randomfile.readByte());//Write file startext = randomfile.getFilePointer(); } //Close various input and output streams randomAccessFile.close(); randomfile.close(); tempfile.delete();//Delete temporary file SimpleDateFormat timed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date nowdate = new Date(); String time = timed.format(nowdate.getTime()); request.setAttribute("info", time+" "+filename+" Uploaded successfully!"); request.setAttribute("filename", filename); request.getRequestDispatcher("/fildeOp.jsp").forward(request, response); }}Download section
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String filename = request.getParameter("filename"); String path = getServletContext().getRealPath("/")+"images/"; File file = new File(path+filename);//File if(file.exists()) { response.setContentType("application/x-msdownload"); //Set the response type, here is the download type response.setHeader("Content-Disposition", "attachment;filename=/""+filename+"/""); //Open InputStream inputStream = new FileInputStream(file); ServletOutputStream outputStream = response.getOutputStream(); byte b[] = new byte[1024]; int n; while((n = inputStream.read(b)) != -1) { outputStream.write(b,0,n); } outputStream.close(); inputStream.close(); }else{ request.setAttribute("result", "The file does not exist! Download failed!"); request.getRequestDispatcher("/fildeOp.jsp").forward(request, response); } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.