最近项目中,在发布商品的时候要用到商品图片上传功能(网站前台和后台都要用到),所以单独抽出一个项目来供其他的项目进行调用 ,对外透露的接口的为两个servlet供外部上传和删除图片,利用到连个jarcommons-fileupload-1.2.1.jar,commons-io-1.4.jar

项目结构如下:

其中com.file.helper主要提供读相关配置文件的帮助类

com.file.servlet 是对外提供调用上传和删除的图片的servlet

com.file.upload 是主要提供用于上传和删除图片的接口

1、FileConst类主要是用读取文件存储路径和设置文件缓存目录 允许上传图片的最大值

package com.file.helper;import java.io.IOException;
import java.util.Properties;public class FileConst {private static Properties properties= new Properties();static{try {properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("uploadConst.properties"));} catch (IOException e) {e.printStackTrace();}}public static String getValue(String key){String value = (String)properties.get(key);return value.trim();}
}

2、ReadUploadFileType读取允许上传图片的类型和判断上传的文件是否符合约束的文件类型

package com.file.helper;import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;import javax.activation.MimetypesFileTypeMap;/*** 读取配置文件* @author Owner**/
public class ReadUploadFileType {private static Properties properties= new Properties();static{try {properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("allow_upload_file_type.properties"));} catch (IOException e) {e.printStackTrace();}}/*** 判断该文件是否为上传的文件类型* @param uploadfile* @return*/public static Boolean readUploadFileType(File uploadfile){if(uploadfile!=null&&uploadfile.length()>0){String ext = uploadfile.getName().substring(uploadfile.getName().lastIndexOf(".")+1).toLowerCase();List<String> allowfiletype = new ArrayList<String>();for(Object key : properties.keySet()){String value = (String)properties.get(key);String[] values = value.split(",");for(String v:values){allowfiletype.add(v.trim());}}// "Mime Type of gumby.gif is image/gif" return allowfiletype.contains( new MimetypesFileTypeMap().getContentType(uploadfile).toLowerCase())&&properties.keySet().contains(ext);}return true;}}

3、FileUpload主要上传和删除图片的功能

package com.file.upload;import java.io.File;
import java.util.Iterator;
import java.util.List;import javax.servlet.http.HttpServletRequest;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.file.helper.FileConst;
import com.file.helper.ReadUploadFileType;public class FileUpload {private static String uploadPath = null;// 上传文件的目录private static String tempPath = null; // 临时文件目录private static File uploadFile = null;private static File tempPathFile = null;private static int sizeThreshold = 1024;private static int sizeMax = 4194304;//初始化static{sizeMax  = Integer.parseInt(FileConst.getValue("sizeMax"));sizeThreshold = Integer.parseInt(FileConst.getValue("sizeThreshold"));uploadPath = FileConst.getValue("uploadPath");uploadFile = new File(uploadPath);if (!uploadFile.exists()) {uploadFile.mkdirs();}tempPath = FileConst.getValue("tempPath");tempPathFile = new File(tempPath);if (!tempPathFile.exists()) {tempPathFile.mkdirs();}}/*** 上传文件 * @param request* @return true 上传成功 false上传失败*/@SuppressWarnings("unchecked")public static boolean upload(HttpServletRequest request){boolean flag = true;//检查输入请求是否为multipart表单数据。boolean isMultipart = ServletFileUpload.isMultipartContent(request);//若果是的话if(isMultipart){/**为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。**/try {DiskFileItemFactory factory = new DiskFileItemFactory();factory.setSizeThreshold(sizeThreshold); // 设置缓冲区大小,这里是4kbfactory.setRepository(tempPathFile);// 设置缓冲区目录ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");//解决文件乱码问题upload.setSizeMax(sizeMax);// 设置最大文件尺寸List<FileItem> items = upload.parseRequest(request);// 检查是否符合上传的类型if(!checkFileType(items)) return false;Iterator<FileItem> itr = items.iterator();//所有的表单项//保存文件while (itr.hasNext()){FileItem item = (FileItem) itr.next();//循环获得每个表单项if (!item.isFormField()){//如果是文件类型String name = item.getName();//获得文件名 包括路径啊if(name!=null){File fullFile=new File(item.getName());File savedFile=new File(uploadPath,fullFile.getName());item.write(savedFile);}}}} catch (FileUploadException e) {flag = false;e.printStackTrace();}catch (Exception e) {flag = false;e.printStackTrace();}}else{flag = false;System.out.println("the enctype must be multipart/form-data");}return flag;}/*** 删除一组文件* @param filePath 文件路径数组*/public static void deleteFile(String [] filePath){if(filePath!=null && filePath.length>0){for(String path:filePath){String realPath = uploadPath+path;File delfile = new File(realPath);if(delfile.exists()){delfile.delete();}}}}/*** 删除单个文件* @param filePath 单个文件路径*/public static void deleteFile(String filePath){if(filePath!=null && !"".equals(filePath)){String [] path = new String []{filePath};deleteFile(path);}}/*** 判断上传文件类型* @param items* @return*/private static Boolean checkFileType(List<FileItem> items){Iterator<FileItem> itr = items.iterator();//所有的表单项while (itr.hasNext()){FileItem item = (FileItem) itr.next();//循环获得每个表单项if (!item.isFormField()){//如果是文件类型String name = item.getName();//获得文件名 包括路径啊if(name!=null){File fullFile=new File(item.getName());boolean isType = ReadUploadFileType.readUploadFileType(fullFile);if(!isType) return false;break;}}}return true;}
}

4、FileUploadServlet上传文件servlet 供外部调用

package com.file.servlet;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.file.upload.FileUpload;@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {FileUpload.upload(request);}}

5、DeleteFileServlet删除图片供外部调用

package com.file.servlet;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.file.upload.FileUpload;@SuppressWarnings("serial")
public class DeleteFileServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String [] file = request.getParameterValues("fileName");FileUpload.deleteFile(file);}}

6、allow_upload_file_type.properties

gif=image/gif
jpg=mage/jpg,image/jpeg,image/pjpeg
png=image/png,image/x-pngimage/x-png,image/x-png
bmp=image/bmp

7、uploadConst.properties

sizeThreshold=4096
tempPath=c\:\\temp\\buffer\\
sizeMax=4194304
uploadPath=c\:\\upload\\
8外部调用

index.jsp

<%@ 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%>"><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">--></head><body><form name="myform" action="http://xxx.com/FileUploadServlet" method="post" enctype="multipart/form-data">File:<input type="file" name="myfile"><br><br><input type="submit" name="submit" value="Commit"></form></body>
</html>

源文件在我上传的资源中进行下载

图片上传系统 common-fileUpload相关推荐

  1. 图片上传系统在淘系中的实践

    传统图片信息的上传渠道一般在pc端的后台或者客户端上直接上传,但是如何在移动端的webview上快速上传图片,并保证图片安全下载这一直是一个挑战. 名词解释 阿里云oss:阿里云对象存储OSS(Obj ...

  2. Jeesite4图片上传

    关于图片上传这个问题,需要注意几个问题 1.我们在代码生成的时候就定义好,允许上传图片,在html页面中的form里就会有,图片上传的这个功能 2.如果之前生代码的时候没有考虑到,后面要是想添加的话, ...

  3. SSM开发书评网29:后台二:wangEditor图片上传;(主要内容是【wangEditor图片上传的文档要求】,【Spring MVC整合FileUpload组件,以实现文件上传功能】)

    说明: (1)本篇博客内容说明:[在后台系统,我们点击新增按钮后,会弹出新增图书对话框]→[该对话框中,包含一个wangEditor富文本编辑器]→[wangEditor富文本编辑器中,可以包含图片] ...

  4. MUI 拍照和从系统相册选择图片上传

    要完成用MUI 拍照和从系统相册选择图片上传的功能,可以理解成有三个功能 1 调用手机相机的功能(可以查看官方API  http://www.html5plus.org/doc/zh_cn/camer ...

  5. 图片上传之fileupload

    最近学习了图片上传这个功能,这个功能比较常见,因此来整理一下,了解上传的基本原理,以便后期遇到图片上传功能可以很快上手. 要说图片上传,我们先来说一下图片上传后存储的两种方式:一种是将图片存储到数据库 ...

  6. 系统中图片上传设计方案

    2019独角兽企业重金招聘Python工程师标准>>> 曾做过一些系统,对于图片上传的相关设计有些疑惑,经过后续的各方面研究,现有了能去除心中困惑的解决方案. 先说说以前做系统时遇到 ...

  7. 微信JSSDK多图片上传并且解决IOS系统上传一直加载的问题

    微信JSSDK多图片上传并且解决IOS系统上传一直加载的问题 参考文章: (1)微信JSSDK多图片上传并且解决IOS系统上传一直加载的问题 (2)https://www.cnblogs.com/co ...

  8. 基于android的图片上传分享系统相册app

    该图片上传分享系统是一款基于安卓的双端程序,客户端采用eclipse作为开发平台,服务端采用了myeclipse作为开发平台,数据库是mysql,主要实现了图片的编辑和上传的功能,界面美观大气,功能技 ...

  9. jeesite同一表单多fileupload图片上传失败,bizType保存失败

    项目场景: 提示:其中一个图片回显失败 jeesite统一表单提交多图片上传显示错误,bizType保存失败 问题描述 同一表单包含2个图片上传,数据库字段保存成功,其中一个预览图回显失败 原因分析: ...

最新文章

  1. python图形用户界面设计报告_19.1 Python图形用户界面开发工具包
  2. Go 1.4 正式版发布,官方正式支持 Android
  3. 【大会】延迟还能再低点吗?不能,但也能
  4. Android系统中通过shell命令实现wifi的连接控制
  5. 为什么不用mysql做数据仓库hdfs_为什么不建议将RAID用于Hadoop HDFS设置?
  6. 字节跳动入局全网搜索;思科回应中国区裁员;IntelliJ IDEA 新版发布! | 极客头条...
  7. Android客户端获取服务器的json数据(二)
  8. 查询Mysql的数据架构信息研究
  9. 驱动该如何入门 关于file_operations和Linux设备模型
  10. 深圳市商务局2022年度中央资金(跨境电子商务企业市场开拓扶持事项)申报指南
  11. python 时频图_python,地震波形、时频图、频谱图计算和显示软件
  12. 每日单词20110502
  13. 淘宝dsr评分如何提升?
  14. JAVA:JDBC数据库编程
  15. 使用ajax报405错误
  16. PMP和MBA、MPA的比较
  17. 2020年汽车驾驶员(初级)考试平台及汽车驾驶员(初级)模拟考试软件
  18. 印欧语系及文化(Indo-European and Culture)英汉双语本(中译本,中文版)
  19. 理解Memcached缓存[转载]
  20. SAP 框架采购订单FO发票验证:

热门文章

  1. 硬件视频编解码基本知识
  2. DM368开发 -- 华为3G/4G模块移植
  3. SDUT-小F的PAT-dfs路径记录
  4. java String类(超详细!)
  5. 【ZZ】梅森素数列表
  6. 聚类分析在用户行为中的实例_聚类分析实例
  7. aria2 bt下载做种问题
  8. ZYNQ axi_uartlitle IP核扩展232或者422
  9. pid控制算法程序c语言,PID控制算法C源码(示例代码)
  10. 研究生初试录取(课程设计)