經測試能用springmvc的檔案上傳下載並解決ie8檔案上傳後提示下載
這兩天領導讓寫一個檔案上傳下載的功能,由於是新手,忙了一天查資料,終於搞定了,經過測試了,給各位看一下,共同學習
一、先寫測試好的上傳功能
首先是實體類
@Data
public class FileUpload {
private byte[] bytes; //輸入位元組流
private String fileName; //檔名字
private String fileuuid;
}
然後是controller
前臺jsp頁面input的name必須與引數名相同,multipartFile
如果是多檔案上傳,引數定義為MultipartFile[] multipartFile就可以,然後裡面遍歷處理
@RequestMapping("/uploadFile") @ResponseBody public ExecuteResult<FileUpload> uploadFile(HttpServletRequest request, MultipartFile multipartFile) { ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();//自己定義的結果集 FileUpload fileUpload = new FileUpload();//自己定義的實體類 try { fileUpload.setFileName(multipartFile.getOriginalFilename());//獲得檔名字,類如: 週報.xls InputStream is = multipartFile.getInputStream();//從multipartFile中獲得輸入流 fileUpload.setBytes(IOUtils.toByteArray(is));//從輸入流中獲得位元組流 IOUtils.closeQuietly(is);//關閉輸入流 execute = fileUploadService.uploadFile(fileUpload);//呼叫service方法存放檔案 response.setContentType("text/json;charset=UTF-8"); //解決ie8上傳後提示下載的問題 } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } catch (Exception e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } return execute; }
然後是service
public ExecuteResult<FileUpload> uploadFile(FileUpload fileUpload) { ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>(); fileUpload.setFileuuid(UUID.randomUUID().toString());//生成uuid String uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL);//此處是專案中自己配置的上傳路徑"d:/" String filePath = uploadPath + fileUpload.getFileuuid();//路徑加UUID File file = new File(filePath);//此檔案會存放在指定資料夾下,檔名字為UUID,並且沒有後綴名 try { if (!new File(filePath).exists()) {//判斷此檔案是否存在了,因為是UUID名字,所以一般不會重複 FileUtils.writeByteArrayToFile(file, fileUpload.getBytes());//呼叫FileUtils的方法,將檔案寫到指定位置,第一個引數為file,第二個引數為輸入位元組流 }else { fileUpload.setFileuuid(UUID.randomUUID().toString()); FileUtils.writeByteArrayToFile(new File(uploadPath + fileUpload.getFileuuid()), fileUpload.getBytes()); } fileUploadMapper.uploadFile(fileUpload); execute.setResult(fileUpload); } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } catch (Exception e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } return execute; }
二、剛才經過測試,下載的也實現了,並解決ie8下載時檔名字亂碼問題,程式碼如下
controller層:
@RequestMapping("/downloadFile")
@ResponseBody
public void fileDownLoad(HttpServletRequest request, HttpServletResponse response, String fileuuid) {
//String fileuuid = request.getParameter("fileuuid");
ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
ServletContext application = request.getSession().getServletContext();
try {
execute = fileUploadService.dowloadFile(fileuuid);
byte[] bytes = execute.getResult().getBytes();
response.reset();
String fileName = execute.getResult().getFileName();
String userAgent = request.getHeader("User-Agent");
//針對IE或者以IE為核心的瀏覽器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
//非IE瀏覽器的處理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
// 先去掉檔名稱中的空格,然後轉換編碼格式為utf-8,保證不出現亂碼,這個檔名稱用於瀏覽器的下載框中自動顯示的檔名
//response.addHeader("Content-Disposition", "attachment;filename=" + new String(execute.getResult().getFileName().replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
//response.addHeader("Content-Length", "" + bytes.length); //此處需要驗證是否正確
//設定檔案MIME型別
response.setContentType(application.getMimeType(fileName));
response.setCharacterEncoding("UTF-8");
OutputStream os = new BufferedOutputStream(response.getOutputStream());
os.write(bytes);
os.flush();
os.close();
} catch (IOException e) {
LOGGER.error("e", e);
} catch (Exception e) {
LOGGER.error("e", e);
}
}
相應前臺
<input type="file" name="multipartFile" id="fileUpload" class="colorblur" onblur="this.className='colorblur';" onfocus="this.className='colorfocus';">
<input type="submit" name="btnUpload" value="上傳" id="btnUpload" class="btn">
- $('#fileToUpload').on('change', function() {
- $.ajaxFileUpload({
- url:'../FileUploadServlet',
- secureuri:false,
- fileElementId:'fileToUpload',//file標籤的id
- dataType: 'json',//返回資料的型別
- data:{fileuuid:'3242354'},//一同上傳的資料
- success: function (data) {
- },
- error:{
- }
- });
- });
最後把mapper也放出來吧,省的你們覺得程式碼不全看不懂。。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="專案.dao.FileUploadMapper">
<resultMap id="fileResultMap" type="。。。。。。。。.FileUpload">
<result property="fileName" column="FILE_NAME" />
<result property="fileuuid" column="FILEUUID" />
</resultMap>
<insert id="uploadFile" parameterType="。。。。。。。。.FileUpload" >
INSERT INTO 表名 (FILE_NAME,FILEUUID)
VALUES (#{fileName},#{fileuuid})
</insert>
<select id="getFileUpload" resultMap="fileResultMap">
SELECT * FROM 表名
WHERE FILEUUID = #{fileuuid}
</select>
</mapper>
另一種寫法
import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @Controller @RequestMapping("/file") public class FileUploadController { private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class); @Resource private FileUploadService fileUploadService; /** * * @param request * @param multipartFile * @return */ @RequestMapping("/uploadFile") public ExecuteResult<FileUpload> uploadFile(HttpServletRequest request, MultipartFile multipartFile, String createBy, String document, String createUserName, HttpServletResponse response) { ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>(); InputStream is = null; FileUpload fileUpload = new FileUpload(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { if (multipartFile == null) { execute.addErrorMessage("上傳檔案為空"); response = checkPro(response, execute); return null; } if (StringUtils.isBlank(createBy) || StringUtils.isBlank(createUserName)) { execute.addErrorMessage("建立人或單據號為空"); response = checkPro(response, execute); return null; } fileUpload.setFileName(multipartFile.getOriginalFilename()); fileUpload.setCreateBy(createBy); fileUpload.setDocument(document); fileUpload.setCreateUserName(createUserName); fileUpload.setCreateDate(df.format(new Date())); is = multipartFile.getInputStream(); //獲得輸入流 fileUpload.setBytes(IOUtils.toByteArray(is)); IOUtils.closeQuietly(is); //關閉輸入流 execute = fileUploadService.uploadFile(fileUpload); response = checkPro(response, execute); response.getWriter().flush(); } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(e.getMessage()); } catch (Exception e) { LOGGER.error("e", e); execute.addErrorMessage(e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(e.getMessage()); } } } return null; } /** * * @param request * @param response */ @RequestMapping("/downloadFile") public void fileDownLoad(HttpServletRequest request, HttpServletResponse response, String fileuuid) { ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>(); ServletContext application = request.getSession().getServletContext(); OutputStream os = null; try { execute = fileUploadService.dowloadFile(fileuuid); byte[] bytes = execute.getResult().getBytes(); response.reset(); String fileName = execute.getResult().getFileName(); String userAgent = request.getHeader("User-Agent"); //針對IE或者以IE為核心的瀏覽器: if (userAgent.contains("MSIE") || userAgent.contains("Trident")) { fileName = java.net.URLEncoder.encode(fileName, "gb2312"); } else { //非IE瀏覽器的處理: fileName = new String(fileName.getBytes("gb2312"), "ISO-8859-1"); } response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName)); // 先去掉檔名稱中的空格,然後轉換編碼格式為utf-8,保證不出現亂碼,這個檔名稱用於瀏覽器的下載框中自動顯示的檔名 //response.addHeader("Content-Disposition", "attachment;filename=" + new String(execute.getResult().getFileName().replaceAll(" ", "").getBytes("utf-8"), "iso8859-1")); //response.addHeader("Content-Length", "" + bytes.length); //此處需要驗證是否正確 //設定檔案MIME型別 response.setContentType(application.getMimeType(fileName)); response.setCharacterEncoding("gb2312"); os = new BufferedOutputStream(response.getOutputStream()); os.write(bytes); os.flush(); } catch (IOException e) { LOGGER.error("e", e); } catch (Exception e) { LOGGER.error("e", e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(e.getMessage()); } } } } @RequestMapping("/deleteFile") @ResponseBody public ExecuteResult<FileUpload> deleteFile(@RequestBody DocumentList documentList) { ExecuteResult<FileUpload> executeResult = new ExecuteResult<FileUpload>(); List<String> documents = documentList.getDocuments(); if (documents.isEmpty() || null == documents.get(0)) { executeResult.addErrorMessage("請至少選擇一條單據"); return executeResult; } return fileUploadService.deleteFile(documents); } @RequestMapping("/getFilesByDocument") @ResponseBody public List<FileUpload> getFilesByDocument(String document) { return fileUploadService.getFilesByDocument(document); } /* 判斷專案是否和.net跨域並處理response */ public HttpServletResponse checkPro(HttpServletResponse response, ExecuteResult<FileUpload> execute) throws IOException { if (APPNAME.OPPLERS.getAppName().equals(Env.getProperty(Env.KEY_SERVER_NAME))) { response.setContentType("text/html; charset=GB2312"); //解決ie8上傳後提示下載的問題 response.getWriter().write(JSONObject.fromObject(execute).toString() + "<script>document.domain='opple.com'</script>"); } else { response.setContentType("text/html; charset=UTF-8"); //解決ie8上傳後提示下載的問題 response.getWriter().write(JSONObject.fromObject(execute).toString()); } return response; } }
service
public class FileUploadServiceImpl implements FileUploadService { private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadServiceImpl.class); @[email protected] private FileUploadMapper fileUploadMapper; /** * 檔案上傳 * @param fileUpload 上傳檔案 * @return ExecuteResult<FileUpload> */ @Override public ExecuteResult<FileUpload> uploadFile(FileUpload fileUpload) { ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>(); fileUpload.setFileuuid(UUID.randomUUID().toString()); String uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL); String filePath = uploadPath + fileUpload.getFileuuid(); File file = new File(filePath); try { if (!new File(filePath).exists()) { FileUtils.writeByteArrayToFile(file, fileUpload.getBytes()); } else { fileUpload.setFileuuid(UUID.randomUUID().toString()); FileUtils.writeByteArrayToFile(new File(uploadPath + fileUpload.getFileuuid()), fileUpload.getBytes()); } fileUploadMapper.uploadFile(fileUpload); fileUpload.setBytes(null); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); fileUpload.setCreateDate(sdf.format(new Date())); execute.setResult(fileUpload); } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } catch (Exception e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } return execute; } /** * 檔案下載 * @param fileuuid uuid * @return ExecuteResult<FileUpload> */ @Override public ExecuteResult<FileUpload> dowloadFile(String fileuuid) { ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>(); InputStream fis = null; try { FileUpload fileUpload = fileUploadMapper.getFileUpload(fileuuid); String uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL); String filePath = uploadPath + fileUpload.getFileuuid(); fis = new BufferedInputStream(new FileInputStream(filePath)); byte[] buffer = IOUtils.toByteArray(fis); fileUpload.setBytes(buffer); execute.setResult(fileUpload); fis.close(); } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } catch (Exception e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { LOGGER.error("e", e); execute.addErrorMessage(LOGGER.toString()); } } } return execute; } @Override public ExecuteResult<FileUpload> deleteFile(List<String> list) { ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>(); String fileuuid = null; String uploadPath = null; String sPath = null; File file = null; boolean flag = false; try { // 判斷目錄或檔案是否存在 for (int i = 0; i< list.size(); i++) { fileuuid = list.get(i); uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL); sPath = uploadPath + fileuuid; file = new File(sPath); if (file.exists()) { // 判斷是否為檔案 if (file.isFile()) { // 為檔案時呼叫刪除檔案方法 flag = deleteFileUtil(sPath); if (flag) { fileUploadMapper.deleteFile(fileuuid); } } } } } catch (Exception e) { LOGGER.error("e", e); execute.addErrorMessage(e.getMessage()); } return execute; } @Override public List<FileUpload> getFilesByDocument(String document) { return fileUploadMapper.getFilesByDocument(document); } /** * 刪除單個檔案 * @param sPath 被刪除檔案的檔名 * @return 單個檔案刪除成功返回true,否則返回false */ public boolean deleteFileUtil(String sPath) { boolean flag = false; File file = new File(sPath); // 路徑為檔案且不為空則進行刪除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } }
相關推薦
經測試能用springmvc的檔案上傳下載並解決ie8檔案上傳後提示下載
這兩天領導讓寫一個檔案上傳下載的功能,由於是新手,忙了一天查資料,終於搞定了,經過測試了,給各位看一下,共同學習 一、先寫測試好的上傳功能 首先是實體類 @Data public class FileUpload { private byte[] bytes; //
上傳大檔案至阿里雲伺服器解決方案(理論上無限大檔案,支援批量處理)
一、背景 目前本地電腦有一個約120G壓縮檔案資料需要上傳到阿里雲伺服器。 二、方案 1.首先嚐試直接從本地複製檔案到雲伺服器,在檔案比較小的情況下OK。這個大檔案中途若遇到網路不穩定將會異常斷線,pass。 2.其次是將該壓縮拆分至每個少於20G,上傳至百度雲盤,
利用 Javascript 實現上傳圖片並向伺服器獲取圖片路徑後顯示的 demo
由於某些特殊原因,有時需要從服務端請求到圖片路徑,需要給該介面傳遞對應圖片的base64 dataURL,並且有時需要將其上傳圖片的型別統一為 jpeg 格式時,可採用以下方式。 HTM
react-native-image-picker在Android上閃退的解決辦法(上傳頭像base64,壓縮上傳圖片)
問題描述:最近做專案上傳頭像時用到了react-native-image-picker第三方庫,使用的是 base64格式 上傳,在以下配置的情況下,android點選選擇相簿會遇到閃退的問題,找到了
SQL Server 2008 能用機器名連線,不能用IP地址連線問題 的一個解決方法
一開始: telnet IP 1433 連線失敗 接著我在伺服器端 找到 Microsoft SQL Server 2008 -->配置工具--> SQL Server 配置管理器 然後在右鍵點選SQL Server
解決Mac上安裝graphviz並在jupyter notebook上使用報錯
報錯資訊: ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphv 執行環境為macOS High Sierra10.13.6 + python3.5 解決辦法: 首
ssl證書安裝完後,https訪問後下載index檔案,HTTP訪問正常的。Nginx ssl設定後自動下載根目錄的index.php而不是載入
給Nginx安裝ssl證書,https訪問後,重新自動下載index.php檔案。一開始的Nginx的配置檔案如下: #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.
CAD看圖軟體如何下載並安裝到電腦上?
CAD看圖軟體如何下載並安裝到電腦上?之前都給大家介紹了CAD看圖如何進行操作使用的全部步驟了,相信大家都會對CAD看圖有一定的操作熟知了,那麼在電腦上面如何進行CAD看圖軟體的下載及安裝的全部操作,你們知道嗎?今天小編就要來教教大家CAD看圖軟體如何下載並安裝到電腦上面的操作步驟,希望大家能夠熟知,具體操作
python實現讀取檔案英文詞頻統計並寫入到檔案
# _*_ coding: utf-8 _*_ # 作者:dcjmessi import os from collections import Counter # 假設要讀取檔名為read,位於當前路徑 filename = 'read.txt' # 當前程
pySpark讀寫CSV檔案、查重並寫入CSV檔案中
前段時間在研究 pySpark 資料處理,深刻地感受到spark的極大魅力。自己是一個初學者,這篇部落格也只是簡單的完成了幾個簡單的工作任務,哈哈@@不說了上程式碼:from pyspark import SparkConf,SparkContext import csv
PC ubuntu 上編譯qt 並開發樹莓派上的桌面應用
PC ubuntu 上使用qt 開發樹莓派上的桌面應用,從編譯qt原始碼到配置kit,到編譯,到除錯執行測試,再到到寫入樹莓派sdcard 真正的一站式教程,個人覺得這樣的文章對於初學qt和樹莓派的菜鳥們來說,簡直就是福音啊!因為我就是 file:///C:\Users\D\AppData\Local\T
Docker教程系列四:Docker上部署MySQL並解決中文亂碼問題
1下載MySQL映象 如果不指定mysql的版本預設下載mysql8,mysql8的變化比較大,所以還是用mysql5.7吧。 docker pull mysql:5.7 檢視映象: docker images 2建立MySQL容器
Java Web實現檔案打包下載並解決亂碼問題
Java Web實現檔案打包下載詳見程式碼: 作為工具類我封裝在FileUtil裡,解決壓縮亂碼要下載 apache-ant-zip.jar包 JDK中自帶的ZipOutputStream在壓縮檔案時,如果檔名中有中文,則壓縮後的 zip檔案開啟時發現中文檔名變成亂
Android 開啟檔案管理器,並返回選中檔案的path
1: 點選觸發事件: Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.add
php javascript 返回上一頁並重新整理和 返回上一頁不重新整理
js: 返回並重新整理 <script>alert("恭喜您,操作成功!"); window.location.href=document.referrer; </script> 返回不重新整理 <script>alert("恭喜您,操作成功!"); windo
用postMesage實現跨域,並解決Failed to execute 'postMessage' on 'DOMWindow'
前言 看了HTML5的postMessage,覺得好像挺好玩的,突然想要去嘗試下,但是前提就是要有兩個不同的源 源 = 規則(http/https)+主機(localhost/其他域名)+埠號,只要有一個不一樣,那麼兩個網頁就是不同的源,在瀏覽器會實現javascript的
Excel檔案減肥修復終極辦法----解決Excel檔案開啟慢的問題
iamlaosong文 Excel檔案在使用過程中由於各種原因會變得越來越大,有的檔案甚至存在一些問題,導致檔案大,開啟慢,實在讓人頭疼。網上有很多辦法,無非是刪除內容、刪除物件等等,但這些辦法有時難以湊效,如一些隱含的東西或者變異(變壞)的東西是無法刪除的,比如建立一個數
sublime開啟檔案時自動生成並開啟.dump檔案
GBK Encoding Support 沒有安裝前開啟ASNI格式編碼檔案會亂碼,安裝成功重啟則可以開啟正常 關於.dump檔案生成的解釋: 當開啟一個非utf-8格式且包含漢字的檔案時,sublime text 2會自動生成一個dump檔案,檔案修改過程中,
setup : esxi5.1.0 不能用ssh上傳安裝檔案
在esxi5.1.0虛擬主機上安裝作業系統前, 需要向虛擬主機中傳入.iso. 使用SSH Secure Shell Client 向虛擬主機傳iso時, 顯示失敗資訊: Error 8: /vmimages/setupfile/winxpsp3.iso (dst): un
非常牛叉的樓主,自己的問題其實就是答案--用springmvc上傳檔案時報The current request is not a multipart request異常
http://bbs.csdn.net/topics/380167574?page=1 非常牛叉的樓主,自己的問題其實就是答案 原因在於目錄下有一個upload檔案導致的 小弟我用spring3.1.0做了一個上傳檔案的例子,但發現一個奇怪的問題