文件上傳
springmvc中文件上傳需要的第三方包主要有commons-fileupload.jar、commons-io.jar和spring-web.jar。其實現方式代碼如下:
/**
* @param request 請求對象
* @param storePath 存儲目錄(文件夾)
* @return boolean 是否上傳成功
* @throws IllegalStateException
* @throws IOException
* @description 參數不允許爲空
*/
public static boolean upload(HttpServletRequest request, String storePath) throws IllegalStateException, IOException{
//創建一個通用的多部分解析器.
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判斷 request 是否有文件上傳,即多部分請求
if(multipartResolver.isMultipart(request)){
//轉換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iterator = multiRequest.getFileNames();
while(iterator.hasNext()){
MultipartFile file = multiRequest.getFile(iterator.next());
//獲取上傳文件的文件名
String finaName = file.getOriginalFilename();
String path = "";
if(storePath.endsWith(File.separator)){
path += storePath + File.separator + finaName;
}else{
path += storePath + finaName;
}
file.transferTo(new File(path));
}
return true;
}
return false;
}
文件下載
文件下載用JDK自帶jar即可,其代碼如下:
/**
* @Description:默認文件名下載方法(參數不允許爲空)
* @param response 相應對象
* @param filePath 文件路徑
* @throws IOException
*/
public static void download(HttpServletResponse response,String filePath) throws Exception{
File file = new File(filePath);
if(file.isFile()){
download(response, file.getName(), filePath);
}else{
throw new Exception("下載類型不是文件或不存在!");
}
}
/**
* @Description:自定義下載文件名方法(參數不允許爲空)
* @param response 相應對象
* @param downloadName 下載文件名
* @param filePath 文件路徑
* @throws IOException
*/
public static void download(HttpServletResponse response, String downloadName, String filePath) throws Exception{
File file = new File(filePath);
if(file.isFile()){
long fileLength = file.length();
String filaname = new String(downloadName.getBytes("gb2312"),"ISO8859-1");
// 清空response
response.reset();
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition","attachment;filename=\"" + filaname + "\"");
response.setHeader("Content-Length", String.valueOf(fileLength));
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
while (is.read(b) != -1) {
os.write(b);
}
is.close();
os.flush();
os.close();
}else{
throw new Exception("下載類型不是文件或不存在!");
}
}