JspSmartUpload 简略中文API文档

链接:https://blog.csdn.net/weixin_43670802/article/details/105143830

PDF课件 链接:

https://pan.baidu.com/s/1tP4dJV8ZnsoW0BfklahRWw

提取码: 3k5w

我遇到的问题

  • 上传文件为中文名问题(在实际服务器使用时依旧不可用)

    设置前端表单页面**内容显示编码(ContentType Charset、Meta Charset)**为GBKGB2312

    后端request设置字符集编码为GBKGB2312,与前端页面一致。
  • 下载文件为中文名问题

    我利用修改Tomcat服务器配置解决。

    在Server.xml 文件 Connector监听节点中添加属性:URIEncoding=“UTF-8”

    支持中文的编码。

也可以使用

smartUpload.downloadFile(filePath,null,URLEncoder.encode(key,"utf-8"));
  • Servlet中获取PageContext对象问题。
//获取PageContext对象
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, JspWriter.DEFAULT_BUFFER, true);

  • 中文URL问题

    我采用URLEncoder与URLDecoder二次编码解码解决。

思维导图

链接: https://pan.baidu.com/s/1TfsuqQ4lqmScZQ6be8aiTA 提取码: uxvh

项目结构

前端

<%@ page import="java.util.UUID"  contentType="text/html;charset=gbk" pageEncoding="gbk" %><%--
By: Jason.
Date: 3/24/2020 6:17 PM
--%>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",-10);
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="GBK">
<title>超级小白龙的自建云盘Beta版.</title>
<!-- 引入 Bootstrap -->
<link href="<%=request.getContextPath()+"/css/bootstrap.css"%>" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()+"/css/style.css"%>">
</head>
<body>
<div class="page_box"> <form action="<%=request.getContextPath()+"/upload.do"%>" method="post" enctype="multipart/form-data">
<h1 class="form-control">哎呦!客官,您可来啦!</h1>
<label for="id_file_1" class="btn btn-default">文件一</label>
<%-- <label for="id_file_2" class="btn btn-default">文件二</label>--%>
<%-- <label for="id_file_3" class="btn btn-default">文件三</label>--%>
<input id="id_file_1" style="display: none;" type="file" name="file_1"/>
<%-- <input id="id_file_2" style="display: none;" type="file" name="file_2"/>--%>
<%-- <input id="id_file_3" style="display: none;" type="file" name="file_3"/>--%>
<input type="hidden" name="me" value="帅帅的我"/>
<%-- 防止表单重复提交 --%>
<input type="hidden" name="token" value="<%=UUID.randomUUID().toString()%>"/>
<p><input class="btn btn-primary" style="margin-top: 10px" type="submit" value="上传"/></p> </form>
</div> </body>
</html>

后端

package top.lking.servlets;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException; 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 javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder; /**
* @author Jason
* @version 1.0
* @date 3/24/2020 8:57 AM
* @describe:
*/
@WebServlet("/upload.do")
public class FileUploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
doPost(req,resp);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //SmartUpload 仅支持GBK或GB2312编码
request.setCharacterEncoding("gbk");
//设置响应内容类型,告诉浏览器类型与编码
response.setContentType("text/html;charset=utf-8");
try {
//新建SmartUpload实例
SmartUpload smartUpload = new SmartUpload();
//获取PageContext对象
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, JspWriter.DEFAULT_BUFFER, true);
//初始化该实例
smartUpload.initialize(pageContext);
//设置允许的上传类型----如果不符合规则,抛异常
smartUpload.setAllowedFilesList("png,jpg,jpeg");
//设置拒绝的上传类型----如果不符合规则,抛异常---(允许与拒绝的类型仅调用即可)
//smartUpload.setDeniedFilesList("txt,doc,mp3,mp4");
//设置单个文件上传的最大字节大小--1MB
smartUpload.setMaxFileSize(1024*1024);
//设置总文件最大字节大小(设置了单个最大大小,这个便无需调用)--3M
smartUpload.setTotalMaxFileSize(1024*1024*3); //将表单数据加载上传至内存------------获取数据前必须先加载上传至内存
smartUpload.upload(); //表单重复提交处理
//获取会话对象Session
HttpSession session=request.getSession(true);
String session_token=(String)session.getAttribute("token");
String form_token=smartUpload.getRequest().getParameter("token"); System.out.println(form_token);
System.out.println(session_token); //如果表单令牌不为空且与session中的令牌匹配--即表单重复提交
if((form_token!=null&&form_token.equals(session_token))||form_token==null){
//转发至展示页面(注意:在客户端无法直接访问到的,所以服务器端转发)
request.getRequestDispatcher("/WEB-INF/pages/show.jsp").forward(request,response);
}else { System.out.println("我执行了!");
//设置本次令牌
session.setAttribute("token",form_token);
//test
//resp.getWriter().println("正在上传,请稍后···"); //test
//Thread.sleep(3000); //获取文件保存路径
String filePathStr=this.getServletContext().getRealPath("/").replace("\\","/")+"/WEB-INF/files";
//构造文件目录对象
File filePath=new File(filePathStr); //判断是否存在
if(!filePath.exists())
//创建一些列目录
filePath.mkdirs(); //将上传文件加载上传至内存后直接保存入文件
//smartUpload.uploadInFile(); //获取上传文件集合
com.jspsmart.upload.Files files=smartUpload.getFiles();
//获取表单隐藏信息
String hiddenLabel=smartUpload.getRequest().getParameter("me");
//保存入Session
session.setAttribute("files",files);
session.setAttribute("hiddenLabel",hiddenLabel);
//将文件从内存写入硬盘
smartUpload.save(filePath.getAbsolutePath());
//转发至展示页面(注意:在客户端无法直接访问到的,所以服务器端转发)
request.getRequestDispatcher("/WEB-INF/pages/show.jsp").forward(request,response); } }catch (Exception e){
e.printStackTrace();
response.getWriter().println("请不要不按规则来!");
} }
}
package top.lking.servlets;

import com.jspsmart.upload.SmartUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.JspWriter;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder; /**
* @author Jason
* @version 1.0
* @date 3/24/2020 10:38 PM
* @describe:
*/
@WebServlet("/image/translate.do")
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码--仅针对Post请求
//request.setCharacterEncoding("utf-8");
//获取文件名--并通过前端二次编码,后端二次解码 解决中文名问题
String downloadSign=request.getParameter("download");
//采用两次编码并且两次解码
//Tomcat在getParameter时已经自动解码一次,下面我手动解码
String key=URLDecoder.decode(request.getParameter("key"),"utf-8");
//测试
System.out.println("我的名字:"+key); //---------------不使用插件下载-------------------
if(downloadSign!=null){
//设置响应头-附件
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(key,"utf-8"));
}
//设置响应信息MIME类型
response.setContentType("image/png");
//InputStream inputStream=this.getServletContext().getClassLoader().getResourceAsStream("/WEB-INF/files/2018050118刘龙龙.png");
String path=request.getServletContext().getRealPath("/WEB-INF/files/"+key).replace("\\","/");
//InputStream inputStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
//test
System.out.println(path); InputStream inputStream=new FileInputStream(path);
byte[] bytes=new byte[1024]; BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(response.getOutputStream()); int len=-1;
while((len=inputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,len);
} inputStream.close();
//---------------不使用插件下载-------------------
//----------------使用插件下载--------------------
// try {
// //实例对象
// SmartUpload smartUpload = new SmartUpload();
// //初始化
// smartUpload.initialize(JspFactory.getDefaultFactory().getPageContext(this, request, response, null, false, JspWriter.DEFAULT_BUFFER, false));
//
//
// //下载
// //使用类加载器获取,不方便动态获取静态资源
// //String tempPath=ImageServlet.class.getClassLoader().getResource(key).getPath();
// //System.out.println(tempPath);
// //smartUpload.downloadFile(URLDecoder.decode(tempPath,"gbk"));
// String directoryPath=request.getServletContext().getRealPath("/WEB-INF/files/").replace("\\","/");
// //转码一下
// //String filePath=directoryPath+URLDecoder.decode(key,"gbk");
// String filePath=directoryPath+key;
// //测试
// System.out.println(filePath);
// //判断是否是下载
// if(downloadSign!=null){
// //附件下载
// //设置响应头-附件
// //response.setHeader("Content-Disposition","attachment;filename=image.png");
//
// //smartUpload.setContentDisposition("attachment;filename="+key);
// smartUpload.setContentDisposition(null);
//
// }else{
//
// //內镶
// smartUpload.setContentDisposition("inline");
// }
// smartUpload.downloadFile(filePath,null,URLEncoder.encode(key,"utf-8"));
// }catch (Exception e){
// response.setContentType("text/html;charset=utf-8");
//
//
// response.getWriter().println("好了,我崩了,你开心了?");
//
// }
}
}

数据显示

<%@ page import="com.jspsmart.upload.Files" %>
<%@ page import="java.util.Enumeration" %>
<%@ page import="com.jspsmart.upload.File" %>
<%@ page import="java.net.URLEncoder" %><%--
By: Jason.
Date: 3/24/2020 5:06 PM
--%>
<%@ page contentType="text/html;charset=utf-8" language="java" pageEncoding="UTF-8" %>
<%
Files files=(Files)session.getAttribute("files");
Enumeration<File> enumeration=files.getEnumeration();
%>
<html>
<head>
<title>老子还真帅!</title>
<!-- 引入 Bootstrap -->
<link href="<%=request.getContextPath()+"/css/bootstrap.css"%>" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()+"/css/style.css"%>">
</head>
<body> <h1>您上传的文件</h1>
<%
for (;enumeration.hasMoreElements();){
File file=enumeration.nextElement();
if (!file.isMissing()){ %>
<div class="show_box">
<%-- 二次编码,我的中文URL处理编码:utf-8 Tomcat默认解码编码:utf-8--%>
<img src="<%=request.getContextPath()%>/image/translate.do?key=<%=URLEncoder.encode(URLEncoder.encode(file.getFileName(),"utf-8"),"utf-8")%>"/>
<%-- 二次编码,我的中文URL处理编码:utf-8 Tomcat默认解码编码:utf-8--%>
<p><a href="<%=request.getContextPath()%>/image/translate.do?key=<%=URLEncoder.encode(URLEncoder.encode(file.getFileName(),"utf-8"),"utf-8")%>&download=1"><input type="button" class="btn btn-primary" value="下载"/></a><a href="<%=request.getContextPath()%>/"><input type="button" class="btn" value="返回"/></a></p>
</div>
<%
}else{
response.sendRedirect("/");
}
}
%> </body>
</html>

注:小白笔记,如果存在错误之处请在评论区指出,谢谢各位。

JspSmartUpload 简略使用的更多相关文章

  1. JspSmartUpload 简略中文API文档

    感谢原文作者:~数字人生~ 原文链接:https://www.cnblogs.com/mycodelife/archive/2009/04/26/1444132.html 一.JspSmartUplo ...

  2. dede 简略标题调用标签

    一.简略标题调用标签: 1.{dede:field.shorttitle/} 不可以在{dede:arclist}标签中套用,一般放在网页titile处; 2.[field:shorttitle/] ...

  3. Win7+Docker(boo2docker)搭建php开发环境简略

    之所以称谓简略 是不准备配图的意思 嘿嘿! 步骤1: 到docker官网下载Docker Toolbox,并完全安装 步骤2: 安装完成后,运行在桌面新生成的快捷方式:Docker Quickstar ...

  4. 对InvokeAction简略分析了解验证失败为什么Action还会继续执行

    一.前言 有些同学使用AuthorizationFilter来进行用户是否登录验证,如果未登录就跳到登录页. 很简单的一个场景,但是有些同学会发现虽然验证失败了,但是整个Action还会执行一遍. 于 ...

  5. 十个Flex/Air疑难杂症及解决方案简略

    十个Flex/Air疑难杂症及解决方案简略 转自http://blog.sban.us/40.html 最近去一家台企,对方给我出了十道“难道”:在TileList中如果選擇檔過多,會出現捲軸,當拖動 ...

  6. MyEclipse------如何添加jspsmartupload.jar+文件上传到服务器

    下载地址:http://download.csdn.net/detail/heidan2006/182263 如何添加jspsmartupload.jar:右键“Web”工程->properti ...

  7. 织梦dedecms简略标题调用标签用法指南

    我们在使用织梦DEDECMS建站过程中,为了使调用的文章标题简短且相对完整(原文标题太长),只好使用了调用简略标题这个方法,使标题显示为简短标题,指向标题时显示完整的标题.并获得文章静态地址链接 下面 ...

  8. HammerDB数据库压力工具使用简略步骤

    欢迎转载,转载请标明出处:http://blog.csdn.net/notbaron/article/details/38879681 HammerDB数据库压力工具使用简略步骤 尽管没有图,可是文字 ...

  9. Intel CPU命名规则的简略解析

    Intel的CPU命名规则一直不是特别清楚,而网上的很多解读是不准确,甚至是错误的,应该以官方文档为准.所以我在查阅官方资料的基础上,以一种简明扼要的方式记录下来.值得说明的是,这个解析只是简略的,一 ...

随机推荐

  1. [opencv]approxDP多边形逼近获取四边形轮廓信息

    #include "opencv2/opencv.hpp" #include <iostream> #include <math.h> #include & ...

  2. JavaScript交互式网页设计 • 【第2章 JavaScript函数与事件】

    全部章节   >>>> 本章目录 2.1 JavaScript 自定义函数 2.1.1 函数的定义 2.1.2 函数的调用 2.1.3 函数的参数 2.1.4 函数的返回值 2 ...

  3. What's new in Dubbo-go v1.5.1

    近期我们发布了 dubbo-go v1.5.1,虽然是 v1.5 的一个子版本,但相比于 v1.5.0, 社区还是投入了很大人力添加了如下重大改进. 1 应用维度注册模型 在新模型 release 后 ...

  4. [学习笔记] IT项目管理 - 关键路径法

    关键路径法 只有项目网络中最常的或者耗时最多的活动完成之后,项目才能结束,这条最长的活动路线就叫关键路径.组成关键路径的活动称为关键活动. 图形表示 最早开始时间ES 工期Duration 最早结束时 ...

  5. Nginx-正反向代理及负载均衡

    目录 正/反向代理 代理的方式 Nginx代理服务支持的协议 代理实战 部署web01 部署Lb01 Nginx代理常用参数 添加发往后端服务器的请求头信息 代理到后端的TCP连接.响应.返回等超时时 ...

  6. python中类对象、实例对象、类属性、实例属性、类方法、实例方法、静态方法

    类对象.类属性与实例对象.实例属性的区别 在Python中一切皆是对象,类是一个特殊的对象即类对象,描述类的属性称为类属性.类属性在内存中只有一份,在__init__外部定义. 通过类创建的对象称为实 ...

  7. Linux shell 脚本中使用 alias 定义的别名

    https://www.cnblogs.com/chenjo/p/11145021.html 核心知识点: 用 shopt 开启和关闭 alias 扩展 交互模式下alias 扩展默认是开启的,脚本模 ...

  8. 移动端position:fixed 解决方案

    相信不少人做移动端项目的时候都会遇到position:fixed 的坑. 下面提供一个解决方法,不用引入任何其他的js库,纯css解决. 解决问题的关键就是:fixed元素内部必须嵌套一个positi ...

  9. JAVA之G1垃圾回收器

    概述 G1 GC,全称Garbage-First Garbage Collector,通过-XX:+UseG1GC参数来启用,作为体验版随着JDK 6u14版本面世,在JDK 7u4版本发行时被正式推 ...

  10. PkavHTTPFuzzer爆破带验证码的后台密码

    之前对暴力破解这块并没有做系统的总结,况且登录这块也是个重头戏,所以我想总结总结. 环境准备 1.用phpstudy搭建phpwms1.1.2演示环境 2.pkavhttpfuzzer工具 漏洞复现 ...