<form method="post" action="url"
<input type="file" name="uploadFile"/>
<br/><br/>
<input type="submit" value="上傳"/>
</form>
上述前端是一個最簡單的上傳框
後端用springmvc舉例
public BaseResultForm uploadLog(HttpServletRequest request, @RequestParam("uploadFile") CommonsMultipartFile uploadFile) {
String fileName = uploadFile.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);//後綴
InputStream inputStream = null;
inputStream = uploadFile.getInputStream();
}
上述代碼就可以獲取到上傳文件流了
之後我們可以對上傳的文件做操作了
-
比如傳到第三方文件服務去,如阿里的oss,使用工具類,設置好傳參即可上傳下載
-
比如另存到項目路徑裏
String projectPath = request.getServletContext().getRealPath("/");//此處爲項目target/root 路徑
也可以存儲到"D://upload/"等路徑
File fileMakeDir = new File(projectPath + "/日誌轉換/" + randomFileName + "/source");
if (!fileMakeDir.exists()) {
fileMakeDir.mkdirs();
}
InputStream inputStream = null;
os = new FileOutputStream(fileMakeDir.getPath() + "/" + randomFileName + ".txt");
inputStream = uploadFile.getInputStream();
int bytes = 0;
while ((bytes = inputStream.read()) != -1) { //讀取文件
os.write(bytes);
}
os.flush(); //關閉流
inputStream.close();
os.close();
//上述代碼可以實現把上傳的輸入流另存到一個路徑
下面寫幾個工具方法
//獲取某路徑下的全部文件
public void getFiles(String path, List<File> fileList) {
File file = new File(path);
File[] files = file.listFiles();
for (File fileIndex : files) {
if (!fileIndex.exists()) {
throw new NullPointerException("Cannot find " + fileIndex);
} else if (fileIndex.isFile()) {
fileList.add(fileIndex);
} else {
if (fileIndex.isDirectory()) {
getXmlFiles(fileIndex.getAbsolutePath(), fileList);
}
}
}
}
//解壓zip文件
public static void unZipFiles(File zipFile, String descDir) throws IOException {
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解決中文文件夾亂碼
String name = zip.getName().substring(zip.getName().lastIndexOf('\\') + 1, zip.getName().lastIndexOf('.'));
File pathFile = new File(descDir + name);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir + name + "/" + zipEntryName).replaceAll("\\*", "/");
// 判斷路徑是否存在,不存在則創建文件路徑
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
// 判斷文件全路徑是否爲文件夾,如果是上面已經上傳,不需要解壓
if (new File(outPath).isDirectory()) {
continue;
}
// 輸出文件路徑信息
// System.out.println(outPath);
FileOutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
System.out.println("******************解壓完畢********************");
return;
}
//移除某個文件夾下全部文件
private static void removeDir(File dir) {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
removeDir(file);
} else {
System.out.println(file + ":" + file.delete());
}
}
System.out.println(dir + ":" + dir.delete());
}
一般都是使用線程池處理文件的後續操作
ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
Runnable runnable = new DoQualityCheck(projectPath, randomFileName, ossDir, qualityCheckLog, qualityCheckDao, qualityCheckLogMapper);
cacheThreadPool.execute(runnable);//加入到線程池,會自動執行
class XXXimplements Runnable {
private String projectPath;
public XXX(String projectPathr) {
}
@Override
public void run() {
logger.info("開啓新線程===========================================");
}
}
有時要把數據導出到excel
@RequestMapping(method = RequestMethod.GET, value = "exportExcel")
public void exportExcel(HttpServletResponse response) {
try {
List<XXX> XXX= new ArrayList<>();
HSSFWorkbook workbook = new HSSFWorkbook();//創建Excel對象
//創建多個sheet
HSSFSheet sheet = null;
HSSFRow row;
HSSFCell cell;
int maxSheetRowCount = 10000;
int sheetIndex = 1;//記錄額外創建的sheet數量
for (int i = 0; i < qualityCheckDTOList.size(); i++) {
int rowIndexInSheet = i % maxSheetRowCount + 1;// rowIndexInSheet = 0 標題行; 實際數據從rowIndexInSheet = 1開始
if (rowIndexInSheet == 1) {
sheet = workbook.createSheet("xxx");//創建工作表單
row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("xxx");
sheetIndex++;
}
row = sheet.createRow(rowIndexInSheet);
cell = row.createCell(0);
cell.setCellValue("xxx");
cell = row.createCell(1);
cell.setCellValue("xxx");
}
OutputStream output = response.getOutputStream();
String new_filename = URLEncoder.encode("xxx" + xxx, "UTF-8");
// 此處使用utf8編碼
String rtn = "filename=\"" + new_filename + "\"" + ".xls";
response.addHeader("Content-Disposition", "attachment;" + rtn);
workbook.write(output);
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}