1. 程式人生 > >多檔案ajaxfileupload上傳

多檔案ajaxfileupload上傳

大體步驟:

1、選擇檔案(可多次選擇)

2、每次選擇檔案之後,將選中的檔案ajaxfileupload上傳到伺服器臨時資料夾,返回檔名稱,預覽展示

3、全域性變數儲存每次上傳的檔名,刪除上傳檔案時需刪除預覽、全域性變數中的檔名和臨時資料夾中的檔案

4、將需要上傳檔名(全域性變數)傳遞到後臺,如果有其他引數也可同時傳遞

5、根據檔名和臨時資料夾地址將需要上傳的檔案從臨時資料夾複製打需要上傳目錄下,之後刪除臨時資料夾中的檔案

例項:

檔案處理工具類:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import 
java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /**
* * <p> * Title: 檔案處理工具類 * </p> * <p> * Description:實現檔案的簡單處理,複製檔案、目錄等 * </p> * <p> * Copyright: Copyright (c) 2005 * </p> * <p>o * Company: www.easyjf.com * </p> * * @author 天一 * @version 1.0 */ public class FileUtil { /** * 複製目錄下的檔案(不包括該目錄)到指定目錄,會連同子目錄一起復制過去。
* * @param targetDir * @param path */ public static void copyFileFromDir(String targetDir, String path) { File file = new File(path); createFile(targetDir, false); if (file.isDirectory()) { copyFileToDir(targetDir, listFile(file)); } } /** * 複製目錄下的檔案(不包含該目錄和子目錄,只複製目錄下的檔案)到指定目錄。 * * @param targetDir * @param path */ public static void copyFileOnly(String targetDir, String path) { File file = new File(path); File targetFile = new File(targetDir); if (file.isDirectory()) { File[] files = file.listFiles(); for (int i=0;i<files.length;i++) { File subFile = files[i]; if (subFile.isFile()) { copyFile(targetFile, subFile); } } } } /** * 複製目錄到指定目錄。targetDir是目標目錄,path是源目錄。 * 該方法會將path以及path下的檔案和子目錄全部複製到目標目錄 * * @param targetDir * @param path */ public static void copyDir(String targetDir, String path) { File targetFile = new File(targetDir); createFile(targetFile, false); File file = new File(path); if (targetFile.isDirectory() && file.isDirectory()) { copyFileToDir(targetFile.getAbsolutePath() + "/" + file.getName(), listFile(file)); } } public static void copyFileToDir(String targetDir, String filePath) { String[] filePaths = new String[]{filePath}; copyFileToDir(targetDir, filePaths); } /** * 複製一組檔案到指定目錄。targetDir是目標目錄,filePath是需要複製的檔案路徑 * * @param targetDir * @param filePath */ public static void copyFileToDir(String targetDir, String[] filePath) { if (targetDir == null || "".equals(targetDir)) { System.out.println("引數錯誤,目標路徑不能為空"); return; } File targetFile = new File(targetDir); if (!targetFile.exists()) { targetFile.mkdir(); } else { if (!targetFile.isDirectory()) { System.out.println("引數錯誤,目標路徑指向的不是一個目錄!"); return; } } if(filePath!=null){ for (int i=0;i<filePath.length;i++) { String path = filePath[i]; File file = new File(path); if (file.isDirectory()) { copyFileToDir(targetDir + "/" + file.getName(), listFile(file)); } else { copyFileToDir(targetDir, file, ""); } } } } /** * 複製檔案到指定目錄。targetDir是目標目錄,file是原始檔名,newName是重新命名的名字。 * * @param targetDir * @param file * @param newName */ public static void copyFileToDir(String targetDir, File file, String newName) { String newFile = ""; if (newName != null && !"".equals(newName)) { newFile = targetDir + "/" + newName; } else { newFile = targetDir + "/" + file.getName(); } File tFile = new File(newFile); copyFile(tFile, file); } /** * 複製檔案。targetFile為目標檔案,file為原始檔 * * @param targetFile * @param file */ public static void copyFile(File targetFile, File file) { if (targetFile.exists()) { System.out.println("檔案" + targetFile.getAbsolutePath() + "已經存在,跳過該檔案!"); return; } else { createFile(targetFile, true); } System.out.println("複製檔案" + file.getAbsolutePath() + "到" + targetFile.getAbsolutePath()); try { InputStream is = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(targetFile); byte[] buffer = new byte[1024]; while (is.read(buffer) != -1) { fos.write(buffer); } is.close(); fos.close(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } public static String[] listFile(File dir) { String absolutPath = dir.getAbsolutePath(); String[] paths = dir.list(); String[] files = new String[paths.length]; for (int i = 0; i < paths.length; i++) { files[i] = absolutPath + "/" + paths[i]; } return files; } public static void createFile(String path, boolean isFile){ createFile(new File(path), isFile); } public static void createFile(File file, boolean isFile) { if (!file.exists()) { if (!file.getParentFile().exists()) { createFile(file.getParentFile(), false); } else { if (isFile) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } } else { file.mkdir(); } } } } // 驗證字串是否為正確路徑名的正則表示式 private static String matches = "[A-Za-z]:\\\\[^:?\"><*]*"; // 通過 sPath.matches(matches) 方法的返回值判斷是否正確 // sPath 為路徑字串 /** * 根據路徑刪除指定的目錄或檔案,無論存在與否 *@param sPath 要刪除的目錄或檔案 *@return 刪除成功返回 true,否則返回 false。 */ public static boolean deleteFolder(String sPath) { boolean flag = false; File file = new File(sPath); // 判斷目錄或檔案是否存在 if (!file.exists()) { // 不存在返回 false return flag; } else { // 判斷是否為檔案 if (file.isFile()) { // 為檔案時呼叫刪除檔案方法 return deleteFile(sPath); } else { // 為目錄時呼叫刪除目錄方法 return deleteDirectory(sPath); } } } /** * 刪除單個檔案 * @param sPath 被刪除檔案的檔名 * @return 單個檔案刪除成功返回true,否則返回false */ public static boolean deleteFile(String sPath) { boolean flag = false; if(sPath != null && !"".equals(sPath)){ File file = new File(sPath); // 路徑為檔案且不為空則進行刪除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } } return flag; } /** * 刪除目錄(資料夾)以及目錄下的檔案 * @param sPath 被刪除目錄的檔案路徑 * @return 目錄刪除成功返回true,否則返回false */ public static boolean deleteDirectory(String sPath) { //如果sPath不以檔案分隔符結尾,自動新增檔案分隔符 if (!sPath.endsWith(File.separator)) { sPath = sPath + File.separator; } File dirFile = new File(sPath); //如果dir對應的檔案不存在,或者不是一個目錄,則退出 if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } boolean flag = true; //刪除資料夾下的所有檔案(包括子目錄) File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { //刪除子檔案 if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) { break; } } //刪除子目錄 else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) { break; } } } if (!flag) { return false; } //刪除當前目錄 if (dirFile.delete()) { return true; } else { return false; } } public static void main(String[] args) { String path = "D:\\Abc\\123\\Ab1"; FileUtil.createFile(path,false); System.out.println("createFile ok"); path = "D:\\Abc\\124"; boolean result = FileUtil.deleteFolder(path); System.out.println("DeleteFolder "+result); } /** * <p> * Description: 上傳檔案重新命名 * </p> * * @param file * 檔名 * @return 檔案 * @author : gaoying * @update : * @date : 2015-7-26 */ public static File renameFile(File file) { String body = ""; String ext = ""; Date date = new Date(); int pot = file.getName().lastIndexOf("."); if (pot != -1) { // body = date.getTime() + ""; body = UUID.randomUUID().toString().replace("-", ""); ext = file.getName().substring(pot); } else { body = (new Date()).getTime() + ""; ext = ""; } String newName = body + ext; file = new File(file.getParent(), newName); return file; } /** * <p> * Description: 上傳檔案重新命名2 * </p> * * @param file * 檔名 * @return 檔案格式強轉為.png檔案 * @author : gaoying * @update : * @date : 2015-7-26 */ public static File renameFilePng(File file) { String body = ""; String ext = ""; Date date = new Date(); int pot = file.getName().lastIndexOf("."); if (pot != -1) { // body = date.getTime() + ""; body = UUID.randomUUID().toString().replace("-", "").toUpperCase(); ext = ".png"; } else { body = (new Date()).getTime() + ""; ext = ""; } String newName = body + ext; file = new File(file.getParent(), newName); return file; } /**==========start=============檔案分割工具方法================start===============**/ /** * 當前目錄路徑 */ public static String currentWorkDir = System.getProperty("user.dir") + "\\"; /** * 左填充 * * @param str * @param length * @param ch * @return */ public static String leftPad(String str, int length, char ch) { if (str.length() >= length) { return str; } char[] chs = new char[length]; Arrays.fill(chs, ch); char[] src = str.toCharArray(); System.arraycopy(src, 0, chs, length - src.length, src.length); return new String(chs); } /** * 刪除檔案 * * @param fileName * 待刪除的完整檔名 * @return */ public static boolean delete(String fileName) { boolean result = false; File f = new File(fileName); if (f.exists()) { result = f.delete(); } else { result = true; } return result; } /*** * 遞迴獲取指定目錄下的所有的檔案(不包括資料夾) * * @param dirPath * @return */ public static ArrayList<File> getAllFiles(String dirPath) { File dir = new File(dirPath); ArrayList<File> files = new ArrayList<File>(); if (dir.isDirectory()) { File[] fileArr = dir.listFiles(); for (int i = 0; i < fileArr.length; i++) { File f = fileArr[i]; if (f.isFile()) { files.add(f); } else { files.addAll(getAllFiles(f.getPath())); } } } return files; } /** * 獲取指定目錄下的所有檔案(不包括子資料夾) * * @param dirPath * @return */ public static ArrayList<File> getDirFiles(String dirPath) { File path = new File(dirPath); File[] fileArr = path.listFiles(); ArrayList<File> files = new ArrayList<File>(); for (File f : fileArr) { if (f.isFile()) { files.add(f); } } return files; } /** * 獲取指定目錄下特定檔案字尾名的檔案列表(不包括子資料夾) * * @param dirPath * 目錄路徑 * @param suffix * 檔案字尾 * @return */ public static ArrayList<File> getDirFiles(String dirPath, final String suffix) { File path = new File(dirPath); File[] fileArr = path.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { String lowerName = name.toLowerCase(); String lowerSuffix = suffix.toLowerCase(); if (lowerName.endsWith(lowerSuffix)) { return true; } return false; } }); ArrayList<File> files = new ArrayList<File>(); for (File f : fileArr) { if (f.isFile()) { files.add(f); } } return files; } /** * 讀取檔案內容 * * @param fileName * 待讀取的完整檔名 * @return 檔案內容 * @throws IOException */ public static String read(String fileName) throws IOException { File f = new File(fileName); FileInputStream fs = new FileInputStream(f); String result = null; byte[] b = new byte[fs.available()]; fs.read(b); fs.close(); result = new String(b); return result; } /** * 寫檔案 * * @param fileName * 目標檔名 * @param fileContent * 寫入的內容 * @return * @throws IOException */ public static boolean write(String fileName, String fileContent) throws IOException { boolean result = false; File f = new File(fileName); FileOutputStream fs = new FileOutputStream(f); byte[] b = fileContent.getBytes(); fs.write(b); fs.flush(); fs.close(); result = true; return result; } /** * 追加內容到指定檔案 * * @param fileName * @param fileContent * @return * @throws IOException */ public static boolean append(String fileName, String fileContent) throws IOException { boolean result = false; File f = new File(fileName); if (f.exists()) { RandomAccessFile rFile = new RandomAccessFile(f, "rw"); byte[] b = fileContent.getBytes(); long originLen = f.length(); rFile.setLength(originLen + b.length); rFile.seek(originLen); rFile.write(b); rFile.close(); } result = true; return result; } /** * 拆分檔案 * * @param fileName * 待拆分的完整檔名 * @param byteSize * 按多少位元組大小拆分 * @return 拆分後的檔名列表 * @throws IOException */ public List<String> splitBySize(String fileName, int byteSize) throws IOException { List<String> parts = new ArrayList<String>(); File file = new File(fileName); int count = (int) Math.ceil(file.length() / (double) byteSize); int countLen = (count + "").length(); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(count, count * 3, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(count * 2)); for (int i = 0; i < count; i++) { String partFileName = file.getName() + "." + leftPad((i + 1) + "", countLen, '0') + ".part"; threadPool.execute(new SplitRunnable(byteSize, i * byteSize, partFileName, file)); parts.add(partFileName); } return parts; } /** * 合併檔案 * * @param dirPath * 拆分檔案所在目錄名 * @param partFileSuffix * 拆分檔案字尾名 * @param partFileSize * 拆分檔案的位元組數大小 * @param mergeFileName * 合併後的檔名 * @throws IOException */ public void mergePartFiles(String dirPath, String partFileSuffix, int partFileSize, String mergeFileName) throws IOException { ArrayList<File> partFiles = FileUtil.getDirFiles(dirPath, partFileSuffix); Collections.sort(partFiles, new FileComparator()); RandomAccessFile randomAccessFile = new RandomAccessFile(mergeFileName, "rw"); randomAccessFile.setLength(partFileSize * (partFiles.size() - 1) + partFiles.get(partFiles.size() - 1).length()); randomAccessFile.close(); ThreadPoolExecutor threadPool = new ThreadPoolExecutor( partFiles.size(), partFiles.size() * 3, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(partFiles.size() * 2)); for (int i = 0; i < partFiles.size(); i++) { threadPool.execute(new MergeRunnable(i * partFileSize, mergeFileName, partFiles.get(i))); } } /** * 根據檔名,比較檔案 * * @author [email protected] * */ private class FileComparator implements Comparator<File> { @Override public int compare(File o1, File o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } } /** * 分割處理Runnable * * @author [email protected] * */ private class SplitRunnable implements Runnable { int byteSize; String partFileName; File originFile; int startPos; public SplitRunnable(int byteSize, int startPos, String partFileName, File originFile) { this.startPos = startPos; this.byteSize = byteSize; this.partFileName = partFileName; this.originFile = originFile; } @Override public void run() { RandomAccessFile rFile; OutputStream os; try { rFile = new RandomAccessFile(originFile, "r"); byte[] b = new byte[byteSize]; rFile.seek(startPos);// 移動指標到每“段”開頭 int s = rFile.read(b); os = new FileOutputStream(partFileName); os.write(b, 0, s); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 合併處理Runnable * * @author [email protected] * */ private class MergeRunnable implements Runnable { long startPos; String mergeFileName; File partFile; public MergeRunnable(long startPos, String mergeFileName, File partFile) { this.startPos = startPos; this.mergeFileName = mergeFileName; this.partFile = partFile; } @Override public void run() { RandomAccessFile rFile; try { rFile = new RandomAccessFile(mergeFileName, "rw"); rFile.seek(startPos); FileInputStream fs = new FileInputStream(partFile); byte[] b = new byte[fs.available()]; fs.read(b); fs.close(); rFile.write(b); rFile.close(); } catch (IOException e) { e.printStackTrace(); } } } /**==========end===============檔案分割工具方法================end================= * @throws Exception **/ /** * 檔案上傳 * @param f 需要上傳檔案 * @param path folderutil獲取路徑 * @throws Exception */ public static void fileUpload(File f , String path) throws Exception{ InputStream is = new FileInputStream(f); OutputStream out = new FileOutputStream(path); byte[] buffer = new byte[1024];

相關推薦

檔案ajaxfileupload

大體步驟: 1、選擇檔案(可多次選擇) 2、每次選擇檔案之後,將選中的檔案ajaxfileupload上傳到伺服器臨時資料夾,返回檔名稱,預覽展示 3、全域性變數儲存每次上傳的檔名,刪除上傳檔案時需刪除預覽、全域性變數中的檔名和臨時資料夾中的檔案 4、將需要上傳檔名(全域性

使用ajaxFileupload實現檔案批量

轉自:http://blog.csdn.net/zhanglu201112/article/details/17039137 開啟google 搜尋 ‘ajaxFileupload’ ‘多檔案上傳’ 可以搜到許許多多類似的,那我為什麼還要寫一下呢? 一

webupload檔案

前端頁面: <li class="mui-table-view-cell"> <p>營業執照</p> <div class="liBox"> <div class="img" style="width: 1

HTML5實現檔案示例程式碼

程式碼如下:import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.uti

SpringMVC + AJAX 實現檔案非同步

轉自:https://www.jianshu.com/p/f3987f0f471f 今天,我就這個問題來寫一篇如何用 SpringMVC + AJAX 實現的多檔案非同步上傳功能。基本的程式碼還是沿用上篇文章中所用到的專案,需要的朋友可以點選前面的連結檢視。在這裡只貼出關鍵程式碼。 首先

Struts2檔案

Struts2Test.java原始碼: package com.test; import java.io.File; import java.io.FileInputStream; import

Android阿里雲OSS檔案同步和刪除方案

上個專案中使用的是阿里雲OSS,查閱了官方文件,發現居然沒有多檔案上傳相關說明文件,只有一個單檔案非同步上傳的說明。既沒有多檔案上傳,又沒有同步上傳,刪除檔案亦然,凌亂。想到之前做過的七牛雲開發,決定用java遞迴的方式實現多檔案同步上傳和刪除,遞迴有風險,使用需謹慎哈。

jquery-uploadfile的使用(檔案非同步

需求 在頁面端可以在頁面不重新整理情況下上傳多個有大小限制的word檔案,並返回檔案儲存的路徑,同時可以刪除誤上傳的檔案。 效果 解決方案 準備 下載該外掛 該外掛依賴jquery1.9.1版本(其它不清楚) *在jsp頁面中引入樣

檔案批量

在網站後臺開發中並經常需要和上傳打交道,而單一的上傳方式已經不適合,大量相似型別的檔案批量上傳,那如何做到呢?(1)當然第一步首先得封裝下檔案上傳的基本函式uploadFiles()方法(2)第二步,那就編輯簡單的上傳的表單吧?(3)第三步編寫php doAction3.ph

html5 multiple檔案非同步 伺服器接收檔案重複

背景 前端採用html5非同步上傳,後端採用Struts1接收檔案。接收到的檔案存在重複的問題。 解決 1.將非同步上傳改為同步上傳,但不推薦這麼改; xhr.open("POST", url,false); 2.採用程式控制方式,在前一個上傳完才開始上傳下一個,產生一個個

ajaxFileUpload.js插件支持文件的方法

before append status appendto secure del 信息 log inf 前提條件:ajaxFileUpload.js插件多文件上傳步驟:1、修改源碼,(源碼只支持單個文件的上傳):復制代碼 代碼如下: //修改前代碼------- //var

ajaxFileUpload 實現文件(源碼)

quest result 問題: check type make with tel orm 按照原ajaxFileUpload.js是不能多文件上傳的。需要對源碼進行修改:主要修改了fileElementId部分 具體參考 https://blog.csdn.net/itm

系統程序的檢視(相關操作)及臺主機相連進行檔案下載,遠端複製及ssh操作的應用

###系統程序及服務控制### 1.##什麼是程序   程序是指在系統中正在執行的一個應用程式 3.檢視程序 1)圖形方式檢視 gnome-system-monitor 2)程序檢視命令       ps  &nbs

ajaxFileUpload檔案簡單示例

寫在前面:   上傳檔案的方式有很多,最近在做專案的時候,一開始也試用了利用jquery的外掛ajaxFileUpload來上傳大檔案,下面,用一個上傳檔案的簡單例子,記錄下,學習的過程~~~   話不多說,直接上程式碼:   前臺jsp頁面:` <

組input檔案,每組 multiple選擇張圖片可增刪其中任意一張圖片

input 、multiple選擇多張圖片時,需要刪除其中的一張圖片怎麼做,大家都知道 input 中的檔案是不能刪除和更改的,只能清空,這裡我的做法是 定義一個物件儲存器把需要的檔案存在儲存器中 formData,後臺不從Input中讀取,從物件儲存器中獲取檔案,一組圖片使

MultipartHttpServletRequest,ajaxFileUpload檔案,讀取檔案亂碼問題

@RequestMapping(value = "/uploadOrgid", method = RequestMethod.POST, produces = "text/html;charset=UTF-8") @ResponseBody public String upl

10分鐘內教你用Python實現檔案自動到百度雲

一、環境說明 Python 3.7  和 win10系統   二、準備工作 首先我們需要安裝一個包,在cmd命令列介面安裝 bypy包。 pip install bypy 然後安裝成功後,在命令列執行命令 bypy info 會彈出一些類似一下的介

Ajaxfileupload個input圖片

頁面 html <label class="layui-icon">&#xe63c; <input type="file" class="fileicon" value="" title="支援jpg、jpeg、gif、png格式,檔

基於Flask實現檔案功能的例項Web服務

flask是Python中非常輕量的Web框架,允許開發者以非常少的程式碼實現各類的Web應用,本文將簡單例項一個簡單Web的檔案上傳功能的開發。 環境介紹 Centos 7.2, virtual env 下的python 3。 安裝flask

java 執行緒解壓檔案

舉個公司專案開發遇到的一個簡單例子,使用者上傳壓縮檔案到伺服器後,要對該壓縮包進行兩個操作,一是將該壓縮包複製到指定目錄,一是將該壓縮包解壓到另一指定目錄,最終響應使用者提示檔案上傳成功。如果壓縮包很大的話,上傳後進行的複製和解壓功能也會佔用很長時間,使用者就會等待很長的