Java implements methods for uploading files to the server

  • 2020-12-21 18:03:06
  • OfStack

In our web development, there were many times when we needed to upload some native files to the web server.

For example: 1 BBS system, when the user uses this is the system, can upload some of the native pictures, documents to the server above. Then other users can download the files, so that we can program to upload the files ourselves

But a better approach would be to use one of the existing components to help us implement this upload.

Common upload components:

The Apache Commons FileUpload

The JavaZoom UploadBean

jspSmartUpload

upload.jsp

Code;


<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>using commons Upload to upload file </title>
</head>
<style>
* { font-family: " Song typeface "; font-size: 14px }
</style>
<body>
<p align="center">  Please select the file you want to upload </p>
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
 <table border="0" align="center">
 <tr>
 <td> From: </td>
 <td>
 <input name="name" type="text" id="name" size="20" ></td>
 </tr> 
 <tr>
 <td> Upload file: </td>
 <td><input name="file" type="file" size="20" ></td>
 </tr> 
 <tr> 
 <td></td><td>
 <input type="submit" name="submit" value=" submit " >
 <input type="reset" name="reset" value=" reset " >
 </td>
 </tr>
 </table>
</form>
</body>
</html>

FileUploadServlet. java code:


/**
 * 
 */
package com.b510.example;

import java.io.File;
import java.io.IOException;
import java.util.*;


import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 
 * @author XHW
 * 
 * @date 2011-7-26
 * 
 */
public class FileUploadServlet extends HttpServlet {

 private static final long serialVersionUID = -7744625344830285257L;
 private ServletContext sc;
 private String savePath;

 public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 doPost(request, response);
 }
 

 public void init(ServletConfig config) {
 //  in web.xml Set in the 1 Three initialization parameters 
 savePath = config.getInitParameter("savePath");
 sc = config.getServletContext();
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 request.setCharacterEncoding("UTF-8");
 DiskFileItemFactory factory = new DiskFileItemFactory();
 ServletFileUpload upload = new ServletFileUpload(factory);
 try {
 List items = upload.parseRequest(request);
 Iterator itr = items.iterator();
 while (itr.hasNext()) {
 FileItem item = (FileItem) itr.next();
 if (item.isFormField()) {
  System.out.println(" Form parameter name :" + item.getFieldName() + " , form parameter values :" + item.getString("UTF-8"));
 } else {
  if (item.getName() != null && !item.getName().equals("")) {
  System.out.println(" The size of the uploaded file :" + item.getSize());
  System.out.println(" Type of file to upload :" + item.getContentType());
  // item.getName() Returns the full path name of the uploaded file on the client side 
  System.out.println(" The name of the uploaded file :" + item.getName());

  File tempFile = new File(item.getName());

 / / Save path to upload files 
  File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
  item.write(file);
  request.setAttribute("upload.message", " File upload successful! ");
  }else{
  request.setAttribute("upload.message", " No option to upload files! ");
  }
 }
 }
 }catch(FileUploadException e){
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 request.setAttribute("upload.message", " File upload failed! ");
 }
 request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
 }
}

uploadResult. jsp code:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 
 <title>uploadResult</title>
 
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0"> 
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
 -->

 </head>
 
 <body>
 ${requestScope['upload.message'] }
 <a href="/upload/uploadFile.jsp" rel="external nofollow" > Upload a file </a>
 </body>
</html>

web.xml


<servlet>
 <description>This is the description of my J2EE component</description>
 <display-name>This is the display name of my J2EE component</display-name>
 <servlet-name>FileUploadServlet</servlet-name>
 <servlet-class>com.b510.example.FileUploadServlet</servlet-class>

  
 <init-param>
  <param-name>savePath</param-name>
  <param-value>uploads</param-value>
 </init-param>
 </servlet>

 <servlet-mapping>
 <servlet-name>FileUploadServlet</servlet-name>
 <url-pattern>/servlet/fileServlet</url-pattern>
 </servlet-mapping>

This article has been sorted into Java upload operation skills summary, welcome to learn to read.


Related articles: