首先在springmvc.xml
中配置文件上傳的屬性
<!-- 文件上傳的屬性值 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
<property name="uploadTempDir" value="/WEB-INF/tmp"></property>
</bean>
在pom.xml
文件中加入上傳組件的jar
包
<!--文件上傳-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
這兩個xml文件配置完成之後,我們就可以開始來寫我們的前端頁面和後端的控制器代碼了。
我們知道後臺接受的類是MultipartFile
,我們首先來封裝一個文件上傳的工具類,將文件上傳到系統的指定目錄下
package com.test.utils;
import com.test.helper.BaseHelper;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
/**
* 文件上傳工具類.
*
* @author 張俊強~.
* @date 2017/11/15-17:27.
*/
public class FileUploadUtils {
//目前文件上傳的路徑
public static final String tmpFilePath="F:\\temp\\";
public static BaseHelper uploadFile(MultipartFile file){
BaseHelper baseHelper=new BaseHelper();
if (!file.isEmpty()) {
String fileName=file.getOriginalFilename();
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(FileUploadUtils.tmpFilePath+fileName)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.printStackTrace();
baseHelper.setCode(StatusInfoUtils.FAILCODE);
baseHelper.setMsg(StatusInfoUtils.UPLOADFAIL);
}
} else {
baseHelper.setCode(StatusInfoUtils.FAILCODE);
baseHelper.setMsg(StatusInfoUtils.NOFILEFOUND);
}
return baseHelper;
}
}
上面的代碼就可以實現文件的保存了。
下面我們來看看單文件上傳和多文件上傳的功能如何實現吧!
單文件上傳
前臺表單代碼
<%----------------單文件上傳-----------------%>
<form method="POST" enctype="multipart/form-data" action="fileOperation/fileUpload">
選擇文件: <input type="file" name="file"><br/>
<input type="submit" value="上傳">
</form>
後臺業務處理代碼
/**
* 單文件的上傳.
*
* @param file 待上傳的文件
* @return 文件上傳的返回信息
*/
@ResponseBody
@RequestMapping(value = {"fileUpload"})
public BaseHelper fileUploadOperation(@RequestParam("file") MultipartFile file) {
BaseHelper baseHelper= FileUploadUtils.uploadFile(file);
return baseHelper;
}
多文件上傳
前臺表單代碼
<%------------多文件上傳--------------%>
<form method="POST" enctype="multipart/form-data" action="fileOperation/mulFileUpload">
<p>
選擇文件:<input type="file" name="files">
<p>
選擇文件:<input type="file" name="files">
<p>
選擇文件:<input type="file" name="files">
<p>
<input type="submit" value="上傳">
</form>
後臺處理代碼
/**
* 多文件的上傳.
*
* @param files 待上傳的文件組
* @return 文件上傳的返回信息
*/
@ResponseBody
@RequestMapping(value = {"mulFileUpload"})
public BaseHelper mulFileUploadOperation(@RequestParam("files") MultipartFile[] files) {
BaseHelper baseHelper=new BaseHelper();
if (files.length>0) {
for(MultipartFile file:files){
baseHelper=FileUploadUtils.uploadFile(file);
}
} else {
baseHelper.setCode(StatusInfoUtils.FAILCODE);
baseHelper.setMsg(StatusInfoUtils.NOFILEFOUND);
}
return baseHelper;
}
以上就是有關文件上傳的功能的實現了,其中的BaseHelper
和StatusInfoUtils
的工具類代碼如下
BaseHelper
代碼
package com.test.helper;
/**
* 一些基本的返回的信息狀態.
*
* @author 張俊強~.
* @date 2017/11/12-10:14.
*/
public class BaseHelper {
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
private String code="SUCCESS"; //默認是成功
@Override
public String toString() {
return "BaseHelper{" +
"code='" + code + '\'' +
", msg='" + msg + '\'' +
'}';
}
private String msg="操作成功"; //默認是操作成功
}
StatusInfoUtils
的工具類代碼
package com.test.utils;
/**
* 一些狀態信息的靜態類.
*
* @author 張俊強~.
* @date 2017/11/12-10:25.
*/
public final class StatusInfoUtils {
private StatusInfoUtils(){}//增強其不可實例化的能力 最好再私有構造器類拋異常
//返回狀態信息
public static final String SUCCESSCODE="SUCCESS";
public static final String SUCCESSMSG="操作成功";
public static final String FAILCODE="FAIL";
public static final String FAILMSG="操作失敗";
//文件上傳狀態信息
public static final String UPLOADSUCCESS="上傳成功";
public static final String UPLOADFAIL="上傳失敗";
public static final String NOFILEFOUND="未選擇文件";
}
關於文件下載,有兩種方法,一種是通過OutputStream
寫出字節,還有一種是通過PrintWriter
寫出字符。
通過OutputStream
寫出字節
/**
* Download file by output stream.
*
* @param response the response
* @param realPath the real path
* @throws FileNotFoundException the file not found exception
* @throws IOException the io exception
*/
public static void downloadFileByOutputStream(HttpServletResponse response, String realPath)
throws FileNotFoundException, IOException {
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Content-Type","application/octet-stream");
response.setHeader("Accept-Ranges","bytes");
InputStream in = new FileInputStream(realPath);
int len = 0;
byte[] buffer = new byte[1024];
OutputStream out = response.getOutputStream();
//將FileInputStream流寫入到buffer緩衝區
while ((len = in.read(buffer)) > 0) {
//使用OutputStream將緩衝區的數據輸出到客戶端瀏覽器
out.write(buffer, 0, len);
}
in.close();
}
通過PrintWriter
寫出字符
/**
* Download file by print writer.
*
* @param response the response
* @param realPath the real path
* @throws FileNotFoundException the file not found exception
* @throws IOException the io exception
*/
public static void downloadFileByPrintWriter(HttpServletResponse response, String realPath)
throws FileNotFoundException, IOException {
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
FileReader in = new FileReader(realPath);
int len = 0;
char[] buffer = new char[1024];
PrintWriter out = response.getWriter();//獲取PrintWriter輸出流
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);//將緩衝區的數據輸出到客戶端瀏覽器
}
in.close();
}
以上 2017-11-15 22:29 於上海
更新時間:2017-11-25 16:49 添加文件下載代碼