Summary of 2021-03-09-java-Servlet version file upload and download

Why does it appear

  • Person information management, upload avatar
  • Product information management, upload product pictures
  • and many more

Import the jar package

  • Apache provides a component for uploading form files (commons-upload)
  • Also import a dependency package commons-io.jar
  • BeanUtils.jar, copy the data in the map to JavaBean

Form

  • The request method must be post
  • There must be a component for uploading files in the form
  • The form must set enctype="multipart/form-data"

Objects needed to upload files

  • DiskFileItemFactory: an engineering class for file upload
  • ServletFileUpload: the most core class for uploading files
  • IOUtils: Tools for copying files
  • BeanUtils: A tool class for object copy
  • FileItem: the operation class of the form attribute

Case study

  • Single file upload: files with duplicate file names
  • Multiple file upload
  • Multi-element upload in the form: there is a problem with multiple selection boxes in the form

file download

  • Download as a stream
  • Need to set the response header
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
  • The problem of garbled Chinese characters in download

Guess you like

Origin blog.csdn.net/qq_41270550/article/details/113867340