File upload and download (using apache)

1. Preparation

Prepare to import dependencies as shown in the jar package
Insert picture description here

2. Single point file upload

1. Front end

Here is the jsp used, the style is bootstrap, the idea will not change

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<script type="text/javascript">
function fileUpload(id){
     
     
     //创建formdata对象
    var formData = new FormData();
     //给formData对象添加<input>标签,注意与input标签的ID一致
    formData.append("files", $("#file"+id)[0].files[0]);
    console.log(formData);
    $.ajax({
     
     
          url : '${pageContext.request.contextPath}/upload?id='+id,
          type : 'POST',
          data : formData,
          contentType: false,// 当有文件要上传时,此项是必须的,否则后台无法识别文件流的起始位置
          processData: false,// 是否序列化data属性,默认true(注意:false时type必须是post)
          dataType: 'json',//这里是返回类型,一般是json,text等
          clearForm: true,//提交后是否清空表单数据
          success: function(data) {
     
        //提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
          	alert('上传成功');
     	  },
     });
}
//点击button按钮触发input标签
function select_file(id){
     
     
    $("#file"+id).trigger("click");
}
</script>
<div>
	<table class="table table-hover  table-bordered table-striped" style="margin-bottom: 0px;">
		<tr>
		  	<th>序号</th>
		  	<th>课程名称</th>
		  	<th>学分</th>
		  	<th>授课老师</th>
		  	<th>操作</th>
		  </tr>
		  <c:forEach var="course" items="${courseList }" varStatus="status">
		  	<tr>
		  	    <td>${status.index+1 }</td>
		  		<td>${course.courseName }</td>
		  		<td>${course.credit }</td>
		  		<td>${course.tearchName }</td>
		  		<td style="display:none">${course.id}</td>
		  		<td style="display:none"><input type="file" name="file" id="file${course.id}" oninput="fileUpload(${course.id})"></td>
		  		<td><button type="button" class="btn btn-info btn-xs" onclick="select_file(${course.id })">上传</button></td>
		  	</tr>
		  </c:forEach>
	</table>
</div>

Idea: Single-point file upload, hide the file type file, use the click event of the button to trigger the click event of the file text box, change the value, and then trigger the upload through the file type input event.

2. Backend

Here is a complete set for a friend to write, just refer to the ideas, and I won’t go into details about the address mapping.

package com.java1234.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.List;
import java.util.UUID;

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;

import com.java1234.dao.CourseDao;
import com.java1234.model.Course;
import com.java1234.util.DbUtil;

/**
 * Servlet implementation class FileUploadServlet
 */
public class FileUploadServlet extends HttpServlet {
    
    
	
	private DbUtil dbUtil = new DbUtil();
	private CourseDao courseDao = new CourseDao();
	
	
	private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadServlet() {
    
    
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		//设置中文乱码
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 配置上传参数
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		String id = request.getParameter("id");
		try {
    
    
			//获取到前端页面上传文件
			List<FileItem> files = upload.parseRequest(request);
			for (FileItem fileItem : files) {
    
    
			//设置本地地址,通过对象动态获取。
			String path = request.getServletContext().getRealPath("/file");
			System.out.println("path------>"+path);
			File file = new File(String.format("%s/%s",path,id));
			//目录不存在则创建
			if (!file.exists()) {
    
    
				file.mkdirs();
			}
			//修改文件名
			String uuid = UUID.randomUUID().toString();
			//获取文件名
			String fileName = fileItem.getName();
			//获取后缀
			String[] split = fileName.split("\\.");
			String fileType = split[split.length-1];
			//组装全路径
			String filePath = String.format("%s/%s/%s%s",path,id,uuid+".",fileType);
			File storeFile = new File(filePath);
			//进行文件复制
			InputStream is = fileItem.getInputStream();
			FileOutputStream fos = new FileOutputStream(storeFile);
			//缓冲区设置0.5M
			byte[] buffer = new byte[1024*512];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
    
    
			    fos.write(buffer, 0, len);
				fos.flush();
			}
			is.close();
			fos.close();
			CourseDao dao = new CourseDao();
			Connection con;
			try {
    
    
				con = dbUtil.getCon();
				Course course = dao.loadCourseById(con, id);
				course.setSrc(String.format("%s/%s/",path,id));
				courseDao.courseUpdate(con, course);
			} catch (Exception e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	} catch (FileUploadException e) {
    
    
		e.printStackTrace();
	}
}

}

3. File download

1. Front end

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<div>
	<table class="table table-hover  table-bordered table-striped" style="margin-bottom: 0px;">
		<tr>
		  	<th>序号</th>
		  	<th>课程名称</th>
		  	<th>学分</th>
		  	<th>授课老师</th>
		  	<th>操作</th>
		  </tr>
		  <c:forEach var="course" items="${courseList }" varStatus="status">
		  	<tr>
		  	    <td>${status.index+1 }</td>
		  		<td>${course.courseName }</td>
		  		<td>${course.credit }</td>
		  		<td>${course.teacherName }</td>
		  		<td><a href="${pageContext.request.contextPath}/download?id=${course.courseId}">下载</a></td>
		  	</tr>
		  </c:forEach>
	</table>
</div>

2. Backend

Note one thing, I want to download multiple files, but this protocol is not allowed, even if there are multiple files, only one will be downloaded

package com.java1234.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

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


/**
 * Servlet implementation class FileDownload
 */
public class FileDownload extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileDownload() {
    
    
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		//设置中文乱码
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		// 下载列表
        String path = request.getServletContext().getRealPath("/file");
        File downloadFile = new File(String.format("%s/%s", path,id));
        if (!downloadFile.exists()) {
    
    
			downloadFile.mkdirs();
		}
        File[] listFiles = downloadFile.listFiles();
        OutputStream os = response.getOutputStream();
        for(File f: listFiles) {
    
    
        	if (f.isFile()) {
    
    
        		//文件类型
        		String mimeType = this.getServletContext().getMimeType(f.getName());
        		response.setContentType(mimeType);
        		//以下载方式
        		response.setHeader("content-disposition", "attachment;filename="+f.getName());
        		FileInputStream fis = new FileInputStream(f);
        		int length = -1;
        		byte[] buffer = new byte[1024*512];
        		while(((length= fis.read(buffer))!= -1)) {
    
    
        			os.write(buffer, 0, length);
        			os.flush();
        		}
        		fis.close();
			}
        }
        os.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Guess you like

Origin blog.csdn.net/qq_44132240/article/details/104729983
Recommended