This article shares the specific codes for javaweb multi-file upload and zip packaging and downloading for your reference. The specific content is as follows
File upload and download functions are often used in projects. This article summarizes the scenes in the JavaWeb environment, multi-file upload and batch packaging and download functions, including the front desk and backend parts.
First of all, let’s make it clear:
The page cannot be refreshed ajax request directly, and download and upload requests cannot be sent. Uploading and downloading must be implemented based on the entire page request. This function is generally achieved by building form forms in projects.
1. Upload multiple files
The project requirements are to realize the multi-image upload function. After referring to the many plug-in methods found on the Internet, I decided to choose the original Jquery upload solution. Follow the steps below to post the specific code.
1. HTML part (can be omitted to build with js)
<form id="uploadForm" method="post" enctype="multipart/form-data"> <input type="file" hidden name="fileImage" multiple/> <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" id="fileSubmit" onclick="uploadFileMulti()">Upload information</a></form>
There are a few explanations:
1. Enctype = "multipart/form-data" in form
2. In the example, use tags to build submit
2. JS part
var formData = new FormData($("#uploadForm")[0]);formData.append("foldName", "datumList"); //Set the parent folder name formData.append("oderCode", selfOrderCode);formData.append("datumType", datumType);$.ajax({ type: "POST", data: formData, url: "order/datumList/batchInsertDatumLists", contentType: false, processData: false, success: function (result) { if (result.success) { //Clear the box file content $("#fileImage").val(""); var obj = document.getElementById('fileImage'); obj.outerHTML = obj.outerHTML; refreshDatumList(); showSuccessToast(result.message); } else { showWarningToast(result.message); } }, error: function () { showErrorToast('Request failed!') }}); There are a few explanations above:
1. var formData = new FormData($("#uploadForm")[0]);
2. Use formData.append("oderCode", selfOrderCode); to add other parameters
Java backend
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;List<MultipartFile> files = mRequest.getFiles("fileImage");There are a few explanations above:
1. Get the MultipartHttpServletRequest, corresponding to the name of the file tag
2. Batch download of files
In this project, the requirement is to download a batch of files in batches. Use zip to compress the file on the server and then download the file to the client.
For online query, using Java's own file output class cannot solve the problem of garbled file names in compressed files. Solution: Use the ant.jar package. When creating a compressed file, you can set the encoding format of the file, and the problem of garbled file names will be solved.
HTML part (can be omitted to build with js)
<form id="uploadForm" method="post" enctype="multipart/form-data"> <div> <input type="hidden" name="orderCode"/> <input type="hidden" name="datumType"/> <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" onclick="batchDatumListDownLoad()">BatchDown</a> </div></form>
JS part
//Batch download function batchDatumListDownLoad() { var param = {}; param.datumType = $("#datumTypeQ").val(); if (param.datumType == -1) { param.datumType = null; //Query all} param.orderCode = selfOrderCode; $("#uploadForm input[name=orderCode]").val(param.orderCode); $("#uploadForm input[name=datumType]").val(param.datumType); var form = $("#uploadForm")[0]; form.action = "order/datumList/batchDownLoadDatumList"; form.method = "post"; form.submit();//Form Submit}Backend part
public void batchDownLoadDatumList(DatumListVo datumListVo, HttpServletResponse response) { try { //Query file list List<DatumListVo> voList = datumListService.queryDatumLists(datumListVo); //Compress file List<File> files = new ArrayList<>(); for (DatumListVo : voList) { File file = new File(vo.getDatumUrl()); files.add(file); } String fileName = datumListVo.getOrderCode() + "_" + datumListVo.getDatumType() + ".zip"; //Create a temporary file for packaged download on the server side String globalUploadPath = ""; String osName = System.getProperty("os.name"); if (osName.toLowerCase().indexOf("windows") >= 0) { globalUploadPath = GlobalKeys.getString(GlobalKeys.WINDOWS_UPLOAD_PATH); } else if (osName.toLowerCase().indexOf("linux") >= 0 || osName.toLowerCase().indexOf("mac") >= 0) { globalUploadPath = GlobalKeys.getString(GlobalKeys.LINUX_UPLOAD_PATH); } String outFilePath = globalUploadPath + File.separator + fileName; File file = new File(outFilePath); //File output stream FileOutputStream outStream = new FileOutputStream(file); //Compress stream ZipOutputStream toClient = new ZipOutputStream(outStream); //Set the character encoding in the compressed file, otherwise it will become garbled toClient.setEncoding("GBK"); ZipUtil.zipFile(files, toClient); toClient.close(); outStream.close(); ZipUtil.downloadZip(file, response); } catch (Exception e) { e.printStackTrace(); }}Among them ZipUtil.java
/** * Files in the compressed file list* * @param files * @param outputStream * @throws IOException */public static void zipFile(List files, ZipOutputStream outputStream) throws IOException, ServletException { try { int size = files.size(); //files in the compressed list for (int i = 0; i < size; i++) { File file = (File) files.get(i); try { zipFile(file, outputStream); } catch (Exception e) { continue; } } } catch (Exception e) { throw e; }}/** * Write the file to the zip file* * @param inputFile * @param outputstream * @throws Exception */public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException { try { if (inputFile.exists()) { if (inputFile.isFile()) { FileInputStream inStream = new FileInputStream(inputFile); BufferedInputStream bInStream = new BufferedInputStream(inStream); ZipEntry entry = new ZipEntry(inputFile.getName()); outputstream.putNextEntry(entry); final int MAX_BYTE = 10 * 1024 * 1024; //The maximum stream is 10M long streamTotal = 0; //The capacity of the accepting stream int streamNum = 0; //The number of streams that need to be separated int leaveByte = 0; //The number of characters left in the file byte[] inOutbyte; //byte array accepts the data of the file streamTotal = bInStream.available(); //The maximum number of characters of the stream is obtained through the available method streamNum = (int) Math.floor(streamTotal / MAX_BYTE); //The number of characters left to be separated for obtaining the stream file leavesByte = (int) streamTotal % MAX_BYTE; //After splitting the file, the remaining number if (streamNum > 0) { for (int j = 0; j < streamNum; ++j) { inOutbyte = new byte[MAX_BYTE]; //Read in the stream and save it in the byte array bInStream.read(inOutbyte, 0, MAX_BYTE); outputstream.write(inOutbyte, 0, MAX_BYTE); //Write out the stream} } //Write out the remaining stream data inOutbyte = new byte[leaveByte]; bInStream.read(inOutbyte, 0, leaveByte); outputstream.write(inOutbyte); outputstream.closeEntry(); //Closes the current ZIP entry and positions the stream for writing the next entry bInStream.close(); //Close inStream.close(); } } else { throw new ServletException("File does not exist!"); } } catch (IOException e) { throw e; }}/** * Download the packaged file* * @param file * @param response */public static void downloadZip(File file, HttpServletResponse response) { try { // Download the file as a stream. BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath())); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // Clear response response response.reset(); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + file.getName()); toClient.write(buffer); toClient.flush(); toClient.close(); file.delete(); //Delete the generated server-side file} catch (IOException ex) { ex.printStackTrace(); }} The above basically meets the requirements for uploading and downloading files.
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.