1:在jsp頁面的代碼如下:
<%
//定義上載文件的最大字節int MAX_SIZE = 102400 * 102400;
// 創建根路徑的保存變量
String rootPath;
//聲明文件讀入類
DataInputStream in = null;
FileOutputStream fileOut = null;
String photo = null;
//取得客戶端的網絡地址
String remoteAddr = request.getRemoteAddr();
//獲得服務器的名字
String serverName = request.getServerName();
String serverAddress=request.getServletPath();
System.out.println("remoteAddr:" + remoteAddr + " serverName:"
+ serverName+"serverAddress:"+serverAddress);
//取得互聯網程序的絕對地址
String realPath = request.getRealPath("");
System.out.println("realPath:" + realPath);
realPath = realPath.substring(0, realPath.lastIndexOf("\\"));
//創建文件的保存目錄
rootPath = "/Zhuxn/photos/";
SmartUpload upload = new SmartUpload();
upload.initialize(pageContext);
upload.setMaxFileSize(MAX_SIZE);
upload.setTotalMaxFileSize(MAX_SIZE);
upload.setAllowedFilesList("jpg,jpeg,bmp,png");
try {
upload.upload();
photo = rootPath + upload.getFiles().getFile(0).getFileName();
System.out.println("rootPath:" + rootPath);
File fileDir = new File(rootPath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
int count = upload.save(rootPath);
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
%>
說明:由於知識展示代碼片段,可能會出現不能完整運行的問題。
2:上面的代碼依靠了一個第三方的擴展包jspSmartUpload.jar,可以在網上下載。
3:在文件上傳的前臺界面的表單的form屬性上,注意要添加enctype="multipart/form-data",例如:
以上則可以完成文件的上傳,在這裏展示的是上傳圖片。