因為手頭的項目需要 上傳圖片,初次才用比較流行的jspSmartUpload上傳。
畢竟沒有搞過,弄了一個下午,終于將碰到的問題搞定了。
第一個問題,表單設置:method="post",ENCTYPE="multipart/form-data",只能這樣
第二個問題,不能通過request.getParameter()取得取得其他的表單字段值,只能通過SmartUpload.getRequest().getParameter("")取得,否則得到的值始終為null
第三,SmartUpload.getRequest().getParameter("")中如果取得中文轉馬方式為
String name=new String(su.getRequest().getParameter("name").getBytes(),"UTF-8");
這是我試了許多方式,唯一正確的
第四 ,取得其他表單字段的值必要在 // 新建一個SmartUpload對象
SmartUpload su = new SmartUpload();
后面完成,否則出錯
相關代碼入下:希望對大家有所幫組
upload.jsp
<%@ page language="java" pageEncoding="UTF-8" import="java.sql.*,com.jspsmart.upload.*"%>
<jsp:useBean id="date" scope="request" class="util.DateAndTime"/>
<jsp:useBean id="data" scope="request" class="util.DataConnection"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html locale="true">
<head>
<html:base />
<title>upload.jsp</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>
<%
// 新建一個SmartUpload對象
// 新建一個SmartUpload對象
SmartUpload su = new SmartUpload();
// 上傳初始化
su.initialize(pageContext);
// 設定上傳限制
// 1.限制每個上傳文件的最大長度。
su.setMaxFileSize(10000);
// 2.限制總上傳數據的長度。
su.setTotalMaxFileSize(10000);
// 3.設定允許上傳的文件(通過擴展名限制),僅允許doc,txt文件。
su.setAllowedFilesList("gif,jpeg,jpg");
// 4.設定禁止上傳的文件(通過擴展名限制),禁止上傳帶有exe,bat,jsp,htm,html擴展名的文件和沒有擴展名的文件。
su.setDeniedFilesList("exe,bat,jsp,htm,html,asp,php,xml,xhtml");
// 上傳文件
su.upload();
// 將上傳文件全部保存到指定目錄
su.save("/upload");
String pathname=null;
String name=new String(su.getRequest().getParameter("name").getBytes(),"UTF-8");
String link=su.getRequest().getParameter("link");
for(int i=0;i<su.getFiles().getCount();i++)
{
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if(file.isMissing()){
continue;
}
pathname=file.getFileName();
}
String ptime=date.getDate2();
String sql="insert into link(path,content,type,ptime,hotlink)values('"+pathname+"','"+name+"','1','"+ptime+"','"+link+"')";
int ac=data.executeOperate(sql);
if(ac==1)
{
out.println("<script>alert('發布成功!');</script>");
out.println("<script>window.location='uplink.jsp';</script>");
}
%>
</body>
</html:html>
來源:CSDN
新聞熱點
疑難解答