Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use java to upload and download files

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use java to upload and download files". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to upload and download files with java.

Upload of files

Upload: file upload

The client uploads and saves the client's files to the server's hard disk through the file field file of the form

Page

First of all, the uploaded form has the following requirements:

Must have a file domain: input type=file

Form submission method: method=post

Enctype=multipart/form-data of the form

User name, password, user avatar

Servlet

1) first, import the following two jar packages to upload files through commons-fileupload

2) create a factory object DiskFileItemFactory, create a multi-part form parser ServletFileUpload, and pass the constructor to the factory object

3) the parser parses the request object to get a list collection, where the list collection stores a fileItem object, and a fileItem corresponds to a component, that is, a

4) the traversal set combination uses the isFormField () method to determine whether it is an ordinary component, and then focuses on the file domain component

5) get the file name, and use the getRealPath method to obtain the path where the file is uploaded by the server, and create a new folder

6) get the input stream and create the output stream to read and write the file

@ WebServlet (value = "/ user/regist") public class UploadServlet extends HttpServlet {protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/ / create a factory object DiskFileItemFactory factory = new DiskFileItemFactory (); / / create a multipart parser object ServletFileUpload fileUpload = new ServletFileUpload (factory); User user = new User (); FileOutputStream out=null Try {/ / parses the request with a parser object and returns a collection of type FileItem List list = fileUpload.parseRequest (req); for (FileItem fileItem: list) {/ * fileItem.getFieldName ();:: gets the component's name value * fileItem.getName () : get the file name of the file field * fileItem.getSize ();: get the number of bytes of data * fileItem.getString ();: get the data string * fileItem.isFormField ()) : determine whether it is an ordinary component * / / determine whether the part is an ordinary component if (fileItem.isFormField ()) {/ / ordinary component / / get the component name, that is, the value of name String fieldName = fileItem.getFieldName () / / get the value of the component, that is, the value of value String value = fileItem.getString ("utf-8"); if ("username" .equals (fieldName)) {/ / set the attribute user.setUsername (value) of the entity class } else if ("password" .equals (fieldName)) {user.setPassword (value);}} else {/ / File Domain / / get the file name String fielName = fileItem.getName () / / input stream to read data InputStream in = fileItem.getInputStream (); / / set the path written by the file, and use random code to ensure that the picture can be repeated String path=req.getServletContext (). GetRealPath ("/ imgs/" + UUID.randomUUID () + fielName) System.out.println ("file path is:" + path); File file = new File (path); out = new FileOutputStream (file); / / use the copy method of commons-io-1.4.jar 's IOUtils to directly realize file copy IOUtils.copy (in,out) User.setPhoto (file.getName ());} catch (Exception e) {e.printStackTrace ();} finally {if (outdated null) {out.close ();}} req.getSession () .setAttribute ("user", user) Req.getRequestDispatcher ("/ sucess.jsp") .forward (req,resp);}} file download

Page

Just a hyperlink, pass the name of the file you need to download, or enter the path directly in the browser

Ex.: dog 1

Servlet

1) receive parameters and get the file name

2) get the path of the imgs, that is, the path of the folder where the file is stored, then create the file, and pass in the path and file name

3) create an input stream to read the file

4) set the response header, first get the large type of the file according to the file name, set the response header Content-Type to specify the response type, and set the response header Content-Disposition to specify that the file is saved to the local disk as an attachment

5) get the output stream with the response, and read the file to the client

@ WebServlet ("/ user/download") public class DownloadServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding ("UTF-8"); / / get the file name String fileName = request.getParameter ("fileName"); System.out.println (fileName) / / get the path of the folder where the pictures are stored on the server String path2 = request.getServletContext () .getRealPath ("/ imgs"); String path=path2+ "/" + fileName; File file = new File (path); / / create the input stream read file FileInputStream in = new FileInputStream (file) / / get the large type of the file by the file name String type = request.getServletContext (). GetMimeType (fileName); / / set the response header ContentType to specify the response content type response.setHeader ("Content-type", type); / / set the response header Content-Disposition to specify the information response.setHeader to save the response as an attachment ("Content-Disposition", "attachment") Filename= "+ (URLEncoder.encode (fileName," utf-8 ")); ServletOutputStream out = response.getOutputStream (); / / IOUtils.copy (in,out) to read and write files; if (inaccessible null) {in.close ();} so far, I believe you have a deeper understanding of" how to use java to upload and download files ". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report