java使用smartupload組件實(shí)現(xiàn)文件上傳的方法
來(lái)源:易賢網(wǎng) 閱讀:2657 次 日期:2015-02-03 15:01:52
溫馨提示:易賢網(wǎng)小編為您整理了“java使用smartupload組件實(shí)現(xiàn)文件上傳的方法”,方便廣大網(wǎng)友查閱!

這篇文章主要介紹了java使用smartupload組件實(shí)現(xiàn)文件上傳的方法,對(duì)比分析了使用組件與不使用組件實(shí)現(xiàn)文件上傳的區(qū)別,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了java使用smartupload組件實(shí)現(xiàn)文件上傳的方法。分享給大家供大家參考。具體分析如下:

文件上傳幾乎是所有網(wǎng)站都具有的功能,用戶可以將文件上傳到服務(wù)器的指定文件夾中,也可以保存在數(shù)據(jù)庫(kù)中,這里主要說(shuō)明smartupload組件上傳。

在講解smartupload上傳前,我們先來(lái)看看不使用組件是怎么完成上傳的原理的?

廢話不多說(shuō)直接上代碼:

代碼如下:

import java.io.*;

import java.util.*;

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;

public class FileUploadTools {

private HttpServletRequest request = null; // 取得HttpServletRequest對(duì)象

private List<FileItem> items = null; // 保存全部的上傳內(nèi)容

private Map<String, List<String>> params = new HashMap<String, List<String>>(); // 保存所有的參數(shù)

private Map<String, FileItem> files = new HashMap<String, FileItem>();

private int maxSize = 3145728; // 默認(rèn)的上傳文件大小為3MB,3 * 1024 * 1024

public FileUploadTools(HttpServletRequest request, int maxSize,

String tempDir) throws Exception { // 傳遞request對(duì)象、最大上傳限制、臨時(shí)保存目錄

this.request = request; // 接收request對(duì)象

DiskFileItemFactory factory = new DiskFileItemFactory(); // 創(chuàng)建磁盤(pán)工廠

if (tempDir != null) { // 判斷是否需要進(jìn)行臨時(shí)上傳目錄

factory.setRepository(new File(tempDir)); // 設(shè)置臨時(shí)文件保存目錄

}

ServletFileUpload upload = new ServletFileUpload(factory); // 創(chuàng)建處理工具

if (maxSize > 0) { // 如果給的上傳大小限制大于0,則使用新的設(shè)置

this.maxSize = maxSize;

}

upload.setFileSizeMax(this.maxSize); // 設(shè)置最大上傳大小為3MB,3 * 1024 * 1024

try {

this.items = upload.parseRequest(request);// 接收全部?jī)?nèi)容

} catch (FileUploadException e) {

throw e; // 向上拋出異常

}

this.init(); // 進(jìn)行初始化操作

}

private void init() { // 初始化參數(shù),區(qū)分普通參數(shù)或上傳文件

Iterator<FileItem> iter = this.items.iterator();

IPTimeStamp its = new IPTimeStamp(this.request.getRemoteAddr()) ;

while (iter.hasNext()) { // 依次取出每一個(gè)上傳項(xiàng)

FileItem item = iter.next(); // 取出每一個(gè)上傳的文件

if (item.isFormField()) { // 判斷是否是普通的文本參數(shù)

String name = item.getFieldName(); // 取得表單的名字

String value = item.getString(); // 取得表單的內(nèi)容

List<String> temp = null; // 保存內(nèi)容

if (this.params.containsKey(name)) { // 判斷內(nèi)容是否已經(jīng)存放

temp = this.params.get(name); // 如果存在則取出

} else { // 不存在

temp = new ArrayList<String>(); // 重新開(kāi)辟List數(shù)組

}

temp.add(value); // 向List數(shù)組中設(shè)置內(nèi)容

this.params.put(name, temp); // 向Map中增加內(nèi)容

} else { // 判斷是否是file組件

String fileName = its.getIPTimeRand()

+ "." + item.getName().split("\.")[1];

this.files.put(fileName, item); // 保存全部的上傳文件

}

}

}

public String getParameter(String name) { // 取得一個(gè)參數(shù)

String ret = null; // 保存返回內(nèi)容

List<String> temp = this.params.get(name); // 從集合中取出內(nèi)容

if (temp != null) { // 判斷是否可以根據(jù)key取出內(nèi)容

ret = temp.get(0); // 取出里面的內(nèi)容

}

return ret;

}

public String[] getParameterValues(String name) { // 取得一組上傳內(nèi)容

String ret[] = null; // 保存返回內(nèi)容

List<String> temp = this.params.get(name); // 根據(jù)key取出內(nèi)容

if (temp != null) { // 避免NullPointerException

ret = temp.toArray(new String[] {});// 將內(nèi)容變?yōu)樽址當(dāng)?shù)組

}

return ret; // 變?yōu)樽址當(dāng)?shù)組

}

public Map<String, FileItem> getUploadFiles() {// 取得全部的上傳文件

return this.files; // 得到全部的上傳文件

}

public List<String> saveAll(String saveDir) throws IOException { // 保存全部文件,并返回文件名稱,所有異常拋出

List<String> names = new ArrayList<String>();

if (this.files.size() > 0) {

Set<String> keys = this.files.keySet(); // 取得全部的key

Iterator<String> iter = keys.iterator(); // 實(shí)例化Iterator對(duì)象

File saveFile = null; // 定義保存的文件

InputStream input = null; // 定義文件的輸入流,用于讀取源文件

OutputStream out = null; // 定義文件的輸出流,用于保存文件

while (iter.hasNext()) { // 循環(huán)取出每一個(gè)上傳文件

FileItem item = this.files.get(iter.next()); // 依次取出每一個(gè)文件

String fileName = new IPTimeStamp(this.request.getRemoteAddr())

.getIPTimeRand()

+ "." + item.getName().split("\.")[1];

saveFile = new File(saveDir + fileName); // 重新拼湊出新的路徑

names.add(fileName); // 保存生成后的文件名稱

try {

input = item.getInputStream(); // 取得InputStream

out = new FileOutputStream(saveFile); // 定義輸出流保存文件

int temp = 0; // 接收每一個(gè)字節(jié)

while ((temp = input.read()) != -1) { // 依次讀取內(nèi)容

out.write(temp); // 保存內(nèi)容

}

} catch (IOException e) { // 捕獲異常

throw e; // 異常向上拋出

} finally { // 進(jìn)行最終的關(guān)閉操作

try {

input.close(); // 關(guān)閉輸入流

out.close(); // 關(guān)閉輸出流

} catch (IOException e1) {

throw e1;

}

}

}

}

return names; // 返回生成后的文件名稱

}

}

上面代碼便可以完成無(wú)組件上傳。

下面開(kāi)始講解smartupload

smartupload是由網(wǎng)站開(kāi)發(fā)的一套上傳組件包,可以輕松的實(shí)現(xiàn)文件的上傳及下載功能,smartupload組件使用簡(jiǎn)單、可以輕松的實(shí)現(xiàn)上傳文件類型的限制、也可以輕易的取得上傳文件的名稱、后綴、大小等。

smartupload本身是一個(gè)系統(tǒng)提供的jar包(smartupload.jar),用戶直接將此包放到classpath下即可,也可以直接將此包拷貝到TOMCAT_HOMElib目錄之中。

下面使用組件完成上傳

單一文件上傳:

代碼如下:

<html>

<head><title>smartupload組件上傳</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>

<body>

<form action="smartupload_demo01.jsp" method="post" enctype="multipart/form-data">

圖片<input type="file" name="pic">

<input type="submit" value="上傳">

</form>

</body>

</html>

jsp代碼:

smartupload_demo01.jsp

代碼如下:

<%@ page contentType="text/html" pageEncoding="utf-8"%>

<%@ page import="com.jspsmart.upload.*" %>

<html>

<head><title>smartupload組件上傳01</title></head>

<body>

<%

SmartUpload smart = new SmartUpload() ;

smart.initialize(pageContext) ; // 初始化上傳操作

smart.upload(); // 上傳準(zhǔn)備

smart.save("upload") ; // 文件保存

out.print("上傳成功");

%>

</body>

</html>

批量上傳:

html文件

代碼如下:

<html>

<head><title>smartupload組件上傳02</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>

<body>

<form action="smartupload_demo02.jsp" method="post" enctype="multipart/form-data">

圖片<input type="file" name="pic1"><br>

圖片<input type="file" name="pic2"><br>

圖片<input type="file" name="pic3"><br>

<input type="submit" value="上傳">

<input type="reset" value="重置">

</form>

</body>

</html>

jsp代碼

smartupload_demo02.jsp

代碼如下:

<%@ page contentType="text/html" pageEncoding="utf-8"%>

<%@ page import="com.jspsmart.upload.*"%>

<%@ page import="com.zhou.study.*"%>

<html>

<head><title>smartupload組件上傳02</title></head>

<body>

<%

SmartUpload smart = new SmartUpload() ;

smart.initialize(pageContext) ; // 初始化上傳操作

smart.upload() ; // 上傳準(zhǔn)備

String name = smart.getRequest().getParameter("uname") ;

IPTimeStamp its = new IPTimeStamp("192.168.1.1") ; // 取得客戶端的IP地址

for(int x=0;x<smart.getFiles().getCount();x++){

String ext = smart.getFiles().getFile(x).getFileExt() ; // 擴(kuò)展名稱

String fileName = its.getIPTimeRand() + "." + ext ;

smart.getFiles().getFile(x).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;

}

out.print("上傳成功");

%>

</body>

</html>

注意:在TOMCAT_HOME/項(xiàng)目目錄下建立upload文件夾才能正常運(yùn)行!

簡(jiǎn)單上傳操作上傳后的文件名稱是原本的文件名稱。可通過(guò)工具類重命名。

另附上重命名工具類。

代碼如下:

package com.zhou.study ;

import java.text.SimpleDateFormat ;

import java.util.Date ;

import java.util.Random ;

public class IPTimeStamp {

private SimpleDateFormat sdf = null ;

private String ip = null ;

public IPTimeStamp(){

}

public IPTimeStamp(String ip){

this.ip = ip ;

}

public String getIPTimeRand(){

StringBuffer buf = new StringBuffer() ;

if(this.ip != null){

String s[] = this.ip.split("\.") ;

for(int i=0;i<s.length;i++){

buf.append(this.addZero(s[i],3)) ;

}

}

buf.append(this.getTimeStamp()) ;

Random r = new Random() ;

for(int i=0;i<3;i++){

buf.append(r.nextInt(10)) ;

}

return buf.toString() ;

}

public String getDate(){

this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;

return this.sdf.format(new Date()) ;

}

public String getTimeStamp(){

this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS") ;

return this.sdf.format(new Date()) ;

}

private String addZero(String str,int len){

StringBuffer s = new StringBuffer() ;

s.append(str) ;

while(s.length() < len){

s.insert(0,"0") ;

}

return s.toString() ;

}

public static void main(String args[]){

System.out.println(new IPTimeStamp().getIPTimeRand()) ;

}

}

附上使用方法:

代碼如下:

<html>

<head><title>smartupload上傳文件重命名</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head>

<body>

<form action="smartupload_demo03.jsp" method="post" enctype="multipart/form-data">

姓名<input type="text" name="uname"><br>

照片<input type="file" name="pic"><br>

<input type="submit" value="上傳">

<input type="reset" value="重置">

</form>

</body>

</html>

Jsp代碼:

smartupload_demo03.jsp

代碼如下:

<%@ page contentType="text/html" pageEncoding="utf-8"%>

<%@ page import="com.jspsmart.upload.*" %>

<%@ page import="com.zhou.study.*"%>

<html>

<head><title>smartupload</title></head>

<body>

<%

SmartUpload smart = new SmartUpload() ;

smart.initialize(pageContext) ; //初始化上傳操作

smart.upload() ; // 上傳準(zhǔn)備

String name = smart.getRequest().getParameter("uname") ;

String str = new String(name.getBytes("gbk"), "utf-8"); //傳值過(guò)程中出現(xiàn)亂碼,在此轉(zhuǎn)碼

IPTimeStamp its = new IPTimeStamp("192.168.1.1") ; // 取得客戶端的IP地址

String ext = smart.getFiles().getFile(0).getFileExt() ; // 擴(kuò)展名稱

String fileName = its.getIPTimeRand() + "." + ext ;

smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;

out.print("上傳成功");

%>

<h2>姓名:<%=str%></h2>

<img src="https://upload.ynpxrz.com/upload/<%=fileName%>">

</body>

</html>

希望本文所述對(duì)大家的jsp程序設(shè)計(jì)有所幫助。

更多信息請(qǐng)查看IT技術(shù)專欄

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:java使用smartupload組件實(shí)現(xiàn)文件上傳的方法
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門(mén)公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國(guó)考·省考課程試聽(tīng)報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)