smartUpload上传下载文件以及中文乱码

时间:2021-05-23 20:57:01

上传文件

index.jsp

<%-- 
Document : index.jsp
Created on : 2016-8-14, 21:38:06
Author : nenujsj116
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="upload.jsp" method="post" enctype="multipart/form-data" >
输入你的名字:<input type="text" name="yourName"/><br/>
选择上传的文件:<input type="file" name="files"/><br/>
<input type="submit" value="上传">
</form>
</body>
</html>

upload.jsp

<%-- 
Document : upload
Created on : 2016-8-14, 21:39:24
Author : nenujsj116
--%>

<%@page import="cn.edu.nenu.other.IPTimeStamp"%>
<%@page import="com.jspsmart.SmartUpload"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("UTF-8");
SmartUpload sp= new SmartUpload();
IPTimeStamp its = new IPTimeStamp(request.getRemoteAddr());
sp.initialize(pageContext);//初始化上传
sp.upload(); //准备上传
String name = "";
String yourname = sp.getRequest().getParameter("yourName");
name = its.getIPTimeStampRand()+ "." + sp.getFiles().getFile(0).getFileExt();
String fileRealPathandName =request.getServletContext().getRealPath("/")+"images"+java.io.File.separator + name;
sp.getFiles().getFile(0).saveAs(fileRealPathandName);
%>
<img alt="刚刚上传的图片" src="images/<%=name%>">
<%=its.getIPTimeStampRand()%>
<h3><%=yourname%></h3>
<h3><%=fileRealPathandName%></h3>
</body>
</html>
文件下载

download.jsp

<%-- 
Document : download
Created on : 2016-8-18, 23:45:14
Author : nenujsj116
--%>

<%@page import="com.jspsmart.SmartUpload"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String file_link = request.getParameter("link");
SmartUpload su=new SmartUpload();
//初始化
su.initialize(pageContext);
//设定contentDisposition为null以禁止浏览器自动打开文件,
//保证点击连接后是下载文件。若不设定,则下载的文件扩展名为doc时,
//浏览器将自动用word打开。扩展名为pdf时,浏览器将用acrobat打开.
su.setContentDisposition(null);
//下载文件
su.downloadFile(file_link);
response.getOutputStream().close();
%>
</body>
</html>
如果用普通的 smartUpload上传文件,将会出现中文乱码,我试了很多种方法都没用,最后找到一种有效的

中文乱码,原博客

1,上传文件名乱码问题 
解决方法:把smartUpload.java类中的getDataHeader()方法中的

String s = new String(m_binArray, i, (j - i) + 1) 
改为

String s = new String(m_binArray, i, (j - i) + 1,"utf-8")  
2,上传时传的参数乱码 
解决方法: 
把smartUpload.java类中的upload()方法中的

String s11 = new String(m_binArray, m_startData,(m_endData - m_startData) + 1); 
改为

String s11 = new String(m_binArray, m_startData,(m_endData - m_startData) + 1,"utf-8"); 
修改后的 smartUpload包  http://download.csdn.net/detail/yimagudao/9620517可能使用时包名出现问题
整个测试项目地址 http://download.csdn.net/detail/yimagudao/9620518