Apache Commons fileUpload实现文件上传之一

时间:2021-05-20

废话不多说了,直奔主题了。

需要两个jar包:

commons-fileupload.jar

Commons IO的jar包(本文使用commons-io-2.4.jar)

利用Servlet来实现文件上传。

package web.servlet;import java.io.IOException;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 java.io.File;import java.util.Iterator;import java.util.List;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/*** Servlet implementation class UploadServlet*/@WebServlet("/UploadServlet")public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;private String uploadPath = "D:\\temp"; // 上传文件的目录private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录File tempPathFile;public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {try {// Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory();// Set factory constraintsfactory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kbfactory.setRepository(tempPathFile);// 设置缓冲区目录// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Set overall request size constraintupload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MBList<FileItem> items = upload.parseRequest(request);// 得到所有的文件Iterator<FileItem> i = items.iterator();while (i.hasNext()) {FileItem fi = (FileItem) i.next();String fileName = fi.getName();if (fileName != null) {File fullFile = new File(fi.getName());File savedFile = new File(uploadPath, fullFile.getName());fi.write(savedFile);}}System.out.print("upload succeed");} catch (Exception e) {// 可以跳转出错页面e.printStackTrace();}}public void init() throws ServletException {File uploadFile = new File(uploadPath);if (!uploadFile.exists()) {uploadFile.mkdirs();}File tempPathFile = new File(tempPath);if (!tempPathFile.exists()) {tempPathFile.mkdirs();}}}

jsp

<%@ page language="java" contentType="text/html; charset=ISO--"pageEncoding="utf-"%><!DOCTYPE html PUBLIC "-//WC//DTD HTML . Transitional//EN" "http://mit"></form></body></html>

这样就能简单实现一个文件上传功能了,当然这是最最最基本的,继续研究中。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章