Here I use servlet-based files asynchronous upload. I don’t say much nonsense and just upload the code. . .
package com.future.zfs.util;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Iterator;import java.util.List;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.FileUploadBase.SizeLimitExceededException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;@SuppressWarnings("serial")public class FileUploadServlet extends HttpServlet { final long MAX_SIZE = 10 * 1024 * 1024;// Set the maximum uploaded file to 10M // List of file formats allowed to be uploaded final String[] allowtype = new String[] {"jpg","jpeg","gif","txt","doc","docx","mp3","wma","m4a","xls"}; public FileUploadServlet() { super(); } public void destroy() { super.destroy(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // Set the character encoding to UTF-8, so that Chinese character display response.setCharacterEncoding("UTF-8"); // Instantiate a hard disk file factory to configure the upload component ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(4096); // Set the memory size used to temporarily store files when uploading files, here is 4K. More than the part will temporarily exist in the hard disk dfif.setRepository(new File(request.getRealPath("/") + "uploadtemp"));// Set the directory where temporary files are stored, the uploadtemp directory under the root directory of the web // Instantiate the upload component with the above factory ServletFileUpload sfu = new ServletFileUpload(dfif); // Set the maximum upload size sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter(); // Get a list of all upload fields from request List fileList = null; try { fileList = sfu.parseRequest(request); } catch (FileUploadException e) {// Handle file size too large exception if (e instanceof SizeLimitExceededException) { out.println("{message:'File size exceeds the specified size:"+MAX_SIZE+"byte'}"); return; } e.printStackTrace(); } // No file upload if (fileList == null || fileList.size() == 0) { out.println("{message:'Please select upload file'}"); return; } // Get all uploaded files Iterator fileItr = fileList.iterator(); // Loop all files while (fileItr.hasNext()) { FileItem fileItem = null; String path = null; long size = 0; // Get the current file fileItem = (FileItem) fileItr.next(); // Ignore the simple form field instead of the file domain of the uploaded domain (<input type="text" />, etc.) if (fileItem == null || fileItem.isFormField()) { continue; } // Get the full path of the file path = fileItem.getName(); // Get the file size size = fileItem.getSize(); if ("".equals(path) || size == 0) { out.println("{message:'Please select upload file'}"); return; } // Get the file name of the removed path String t_name = path.substring(path.lastIndexOf("//") + 1); // Get the file extension (the full name will be obtained without an extension) String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); // Deny the file type outside the specified file format int allowFlag = 0; int allowedExtCount = allowtype.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowtype[allowFlag].equals(t_ext)) break; } if (allowFlag == allowedExtCount) { String message = ""; for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++){ message+="*." + allowtype[allowFlag] + " "; } out.println("{message:'Please upload the following type of file "+message+"'}"); return; } long now = System.currentTimeMillis(); // Generate the file name saved after upload according to system time String prefix = String.valueOf(now); // The complete path of the saved final file is saved in the upload directory under the root directory of the web u_name = request.getRealPath("/") + "upload/" + prefix + "." + t_ext; // The original file name path=request.getRealPath("/") + "upload/"+path; try { // Save file fileItem.write(new File(path)); response.setStatus(200); out.println("{message:/"File upload successfully. Saved as: " + prefix + "." + t_ext + " File size: " + size + "byte/"}"); } catch (Exception e) { e.printStackTrace(); } } }} web.xml
<servlet> <servlet-name>fileUploadServlet</servlet-name> <servlet-class>com.future.zfs.util.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>fileUploadServlet</servlet-name> <url-pattern>/fileUploadServlet</url-pattern> </servlet-mapping>
Upload page
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/ajaxfileupload.js"></script> <script type="text/javascript"> function ajaxFileUpload() { $("#loading") .ajaxStart(function(){ $(this).show(); })// Show an image when you start uploading the file.ajaxComplete(function(){ $(this).hide(); });//Hide the image after the file is uploaded.$.ajaxFileUpload ( { url:'fileUploadServlet',//The server-side request address used for file upload secureuri:false,//Generally set to false fileElementId:'file',//The id attribute of the file upload space<input type="file" id="file" name="file" /> dataType: 'json',//The return value type is generally set to json success: function (data, status) //The server successfully responds to the processing function { //alert(data.message);//The data in the message is the member variable $('#myspan') defined in struts2. If(typeof(data.error) != 'undefined') { if(data.error != '') { //alert(data.error); $('#myspan').html(data.message); }else { //alert(data.message); $('#myspan').html(data.message); } } }, error: function (data, status, e)//Server response failure handling function { //alert(e); $('#myspan').html(e); } } ) return false; } </script> </head> <body> <img src="images/loading.gif" id="loading" style="display: none;"> <span style="color: red;" id="myspan"></span><br/> <input type="file" id="file" name="file" /> <br /> <input type="button" value="upload" onclick="return ajaxFileUpload();"> <a href="fileDownLoadServlet?filename=address book.xls">Haha, test file download</a> </body></html> It should be noted that when using ajaxFileUpload to upload based on servlet, you need to set response.setContentType("text/html"); although dataType: 'json' is set to json, you still need to set response.setContentType("text/html"); otherwise, the data returned by the server cannot be obtained and a dialog box will pop up.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.