javaweb implementation file upload sample code
- 2020-06-19 10:25:45
- OfStack
This article examples for you to share javaweb file download specific implementation code, for your reference, the specific content is as follows
Sample file upload
Note: The jsp page is encoded as "ES7en-8"
Requirements for file uploads
1.form form, which must be submitted in POST mode
2.enctype="multipart/form-data"
3. There must be < input type="file" / >
Front end jsp page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" >
<title>My JSP 'index.jsp' starting page</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>
<script type="text/javascript">
function addFile(){
var div1=document.getElementById("div1");
div1.innerHTML+="<div><input type='file' /><input type='button' value=' delete ' onclick='deleteFile(this)' /> <br/></div>";
}
function deleteFile(div){
// His grandfather deleted his father
div.parentNode.parentNode.removeChild(div.parentNode);
}
</script>
<body>
<form action="${pageContext.request.contextPath }/servlet/upLoadServlet" method="post" enctype="multipart/form-data">
Description of the document: <input type="text" name ="description" /><br/>
<div id="div1">
<div>
<input type="file" name ="file" /><input type="button" value=" add " onclick="addFile()" /><br/>
</div>
</div>
<input type="submit" />
</form>
</body>
</html>
servlet for file upload
package com.learning.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
import org.apache.commons.io.FilenameUtils;
/**
* Servlet implementation class UpLoadServlet
*/
@WebServlet("/servlet/upLoadServlet")
public class UpLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// File upload
// Determine whether file uploads are supported
boolean isMultipartContent = ServletFileUpload
.isMultipartContent(request);
if (!isMultipartContent) {
throw new RuntimeException(" Does not support ");
}
// create 1 a DiskFileItemfactory The factory class
DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
// create 1 a ServletFileUpload Core object
ServletFileUpload fileUpload=new ServletFileUpload(diskFileItemFactory);
// Set Chinese scrambling code
fileUpload.setHeaderEncoding("UTF-8");
// Set up the 1 File size per file
fileUpload.setFileSizeMax(1024*1024*3); // Size of the 3M
// Sets the total file size
//fileUpload.setSizeMax(1024*1024*10);// Size of the 10M
try {
//fileload parsing request Request, return list<FileItem> A collection of
List<FileItem> fileItems = fileUpload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
// Is a text field ( Functions that handle text fields )
processFormField(fileItem);
}else {
// File domain ( Functions that handle file fields )
processUpLoadField1(fileItem);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
/**
* @param fileItem
*
*/
private void processUpLoadField1(FileItem fileItem) {
try {
// Gets the file read stream
InputStream inputStream = fileItem.getInputStream();
// Get the file name
String fileName = fileItem.getName();
// File name processing
if (fileName!=null) {
fileName.substring(fileName.lastIndexOf(File.separator)+1);
}else {
throw new RuntimeException(" File name does not exist ");
}
// Repeat processing for filenames
// fileName=new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
fileName=UUID.randomUUID()+"_"+fileName;
// Date of classification
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
String date = simpleDateFormat.format(new Date());
// Create a directory
File parent=new File(this.getServletContext().getRealPath("/WEB-INF/upload/"+date));
if (!parent.exists()) {
parent.mkdirs();
}
// Upload a file
fileItem.write(new File(parent, fileName));
// Delete temporary files (if the upload file is too large, it will be generated .tmp Temporary documents)
fileItem.delete();
} catch (IOException e) {
System.out.println(" Upload failed ");
e.printStackTrace();
} catch (Exception e) {
}
}
/**
* @param fileItem
*/
// File domain
private void processUpLoadField(FileItem fileItem) {
try {
// Gets the file input stream
InputStream inputStream = fileItem.getInputStream();
// Get is the name of the file
String filename = fileItem.getName();
// Handle file names
if (filename!=null) {
// filename.substring(filename.lastIndexOf(File.separator)+1);
filename = FilenameUtils.getName(filename);
}
// Get the path and create a directory to hold the files
String realPath = this.getServletContext().getRealPath("/WEB-INF/load");
File storeDirectory=new File(realPath);// It represents both a file and a directory
// Create the specified directory
if (!storeDirectory.exists()) {
storeDirectory.mkdirs();
}
// Prevent filename 1 sample
filename=UUID.randomUUID()+"_"+filename;
// Directory break up To prevent the same 1 There are too many files under the directory file to find easily
// Store uploaded files by date
//storeDirectory = makeChildDirectory(storeDirectory);
// Multiple directories hold uploaded files
storeDirectory = makeChildDirectory(storeDirectory,filename);
FileOutputStream fileOutputStream=new FileOutputStream(new File(storeDirectory, filename));
// Reads the file and outputs it to the specified directory
int len=1;
byte[] b=new byte[1024];
while((len=inputStream.read(b))!=-1){
fileOutputStream.write(b, 0, len);
}
// Close the stream
fileOutputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Sort by date
private File makeChildDirectory(File storeDirectory) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
String date = simpleDateFormat.format(new Date());
// Create a directory
File childDirectory=new File(storeDirectory, date);
if (!childDirectory.exists()) {
childDirectory.mkdirs();
}
return childDirectory;
}
// Multi-level directory
private File makeChildDirectory(File storeDirectory, String filename) {
filename=filename.replaceAll("-", "");
File childDirectory =new File(storeDirectory, filename.charAt(0)+File.separator+filename.charAt(1));
if (!childDirectory.exists()) {
childDirectory.mkdirs();
}
return childDirectory;
}
// Text field
private void processFormField(FileItem fileItem) {
// For the text field of Chinese gibberish, can be used new String() Way to solve
try {
String fieldName = fileItem.getFieldName();// Field names in the form name , such as description
String fieldValue = fileItem.getString("UTF-8");//description In the value
// fieldValue=new String(fieldValue.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(fieldName +":"+fieldValue);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}