Partial realization of file upload and download in Java web project

Memorabilia-Late Night

In the middle of the night, I will record what I have learned about how to upload and download files using a browser like a server directory in a JavaWeb project.

So-called file upload and download

The essence is to read and write files in the form of I/O streams. Streaming from A to B, after restoration, file transfer can be realized.
The realization process is as follows:

  1. Select and submit the file to upload.
  2. The server receives in streaming form.
  3. Write to the corresponding path.
    The main body is these three steps, and the specific corresponding code logic is as follows:

//在jsp页面添加表单,并且必须有enctype="multipart/form-data"属性
 <form action="saveFile" method="post" enctype="multipart/form-data">
      请选择文件:<input type="file" name="fileName" value=""><br>
      <input type="submit" name="提交">
    </form>

The effect diagram is as follows
Realization effect diagram
②The
second step may be a little complicated, but it is relatively easy.

//在对应控制类中,以流形式接收该文件
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> itemList = upload.parseRequest(req);
for(var item : itemList){
    
    //加强for循环是为了防止表单一次性有过多文件传输
	String realName = item.getName();//注意此处获得的是文件真实文件名,也就是从盘符开始的
	String[] name = realName.split("\\\\");//此处四个\是因为\自身本为转义符,再加上split方法的特殊性。有兴趣的伙伴可以自行了解
	realName = name[name.length-1];//这才是文件的名称
	InputStream inputStream = item.getInputStream();//以流形式接收到文件自身内容
}

At this point, the second step is completed. But what needs to be said is the first two lines of code in particular. In fact, an externally encapsulated jar package is used (the address is at the back). After all, you can see farther by standing on the shoulders of giants. The logic is more complicated, and the author himself is still a little dazed, so I won’t explain it.
③In
fact, there are two ways to realize this step. The first is simple, and interested partners can look at the second principle.

item.write(new File("D://test/"+realFileName));//在上一个for循环中加入这一行就成功了,当然路径自选。

The underlying principle is nothing more than

OutputStream outputStream = new FileOutputStream("D://test/"+realFileName);//新建文件输入
	byte[] b = new byte[1024];//设定一次性写入大小
	int length = inputStream.read(b);//I/O流方式进行读取
	while(length!=-1){
    
    
		outputStream.write(b,0,length);//循环写入
		outputStream.flush();
		length = inputStream.read(b);
	}

In this way, we have realized the file transfer to the server. After my boring test, it is possible to transfer file data between different computers in the local area network. If you join the public IP, you won't know. When I have a need, let's fill in the hole in this question.

The principle of downloading files is almost the same as uploading.

  1. Send the file name to be downloaded in the browser
  2. The server receives and creates an input stream to read the contents of the file
  3. The corresponding object creates an output stream and responds the content back to the browser. The
    first step is not repeated here. The second step is more troublesome is to respond to the browser, so you need to set some response header information and format
String fileName = request.getParameter("fileName");//首先get到文件名
InputStream inputStream = new FileInputStream("D://test/"+fileName);//在服务器路径下读取该文件
 fileName = URLEncoder.encode(fileName,"UTF-8");//处理中文
 //  调用静态常量进行拼接字符串
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-disposition","attachment;filename="+fileName);
        将内容响应回浏览器
        OutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int length = inputStream.read(b);
        while(length!=-1){
    
    
            outputStream.write(b,0,length);
            outputStream.flush();
            length = inputStream.read(b);
        }

Although the means of realization are slightly different, they are almost the same from the ideological level. It's just that the flow of files is different.
In the middle of the night, my own mind is not very clear. Record the "big" events of a certain period of time, and I hope it will help you a little bit. I
almost forgot the address of the jar package.
Commons-fileupload.jar
commons-io.jar is a package provided by the apache organization.
http://commons .apache.org/
choose to download fileupload and io

Guess you like

Origin blog.csdn.net/qq_42673041/article/details/108655555