文件上傳
apache 上傳組件方案
單文件上傳
-
添加依賴
<!--apache組件文件上傳--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
-
在springMVC當(dāng)中要注冊一個文件上傳解析器
<!--文件上傳解析器 id必須為multipartResolver,原因是源代碼里面寫死了這個名字 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--單個文件最大上傳大小--> <property name="maxUploadSizePerFile" value="20000000"></property> <!--指定上傳編碼--> <property name="defaultEncoding" value="UTF-8"></property> <!--定義最大文件大小 總的,單位為bytes--> <property name="maxUploadSize" value="200000000"></property> </bean>
-
準(zhǔn)備上傳頁面
<form action="${ctx}/file/upload" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="file"> <input type="submit" value="提交"> </form>
-
后臺
@Controller @RequestMapping("/file") public class FileController { /*在Windows下的路徑分隔符(\)和在Linux下的路徑分隔符(/)是不一樣的, 當(dāng)直接使用絕對路徑時携栋,跨平臺會報No Such file or diretory異常。 File.separator能解決這個問題 */ private static String uploadPath = "E:" + File.separator; //入?yún)⒕涂梢赃x擇上傳的文件 @RequestMapping("/upload") public String upload(@RequestParam("file")MultipartFile multipartFile,Model model){ //1、傳到那里去 2伴嗡、我傳什么東西 3、傳的細(xì)節(jié) System.out.println("uploadPath=" + uploadPath); //1从铲、判斷 if(multipartFile != null && !multipartFile.isEmpty()){ //不能為空 //2瘪校、獲取原始的文件名 String originalFilename = multipartFile.getOriginalFilename(); System.out.println(originalFilename); //3、先截取文件的文件名前綴名段,不帶后綴 String fileNamePrefix = originalFilename.substring(0,originalFilename.lastIndexOf(".")); //4阱扬、加工處理文件名,將原文件名+時間戳 String newFileNamePrefix = fileNamePrefix + new Date().getTime(); //5伸辟、得到新文件名 String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf(".")); //6麻惶、構(gòu)建文件對象 File file = new File(uploadPath + newFileName); //7、上傳操作 try { multipartFile.transferTo(file); model.addAttribute("fileName",newFileName); } catch (IOException e) { e.printStackTrace(); } } return "uploadSuc"; } }
多文件上傳
@RequestMapping("/upload2")
public String upload2(@RequestParam("file")MultipartFile[] multipartFiles,Model model){
List<String> fileNames = new ArrayList<>();
if(multipartFiles != null && multipartFiles.length > 0){
//遍歷
for(MultipartFile multipartFile : multipartFiles){
//1信夫、傳到那里去 2窃蹋、我傳什么東西 3、傳的細(xì)節(jié)
System.out.println("uploadPath=" + uploadPath);
//1静稻、判斷
if(multipartFile != null && !multipartFile.isEmpty()){
//不能為空
//2警没、獲取原始的文件名
String originalFilename = multipartFile.getOriginalFilename();
System.out.println(originalFilename);
//3、先截取文件的文件名前綴振湾,不帶后綴
String fileNamePrefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));
//4杀迹、加工處理文件名,將原文件名+時間戳
String newFileNamePrefix = fileNamePrefix + new Date().getTime();
//5押搪、得到新文件名
String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf("."));
//6树酪、構(gòu)建文件對象
File file = new File(uploadPath + newFileName);
//7浅碾、上傳操作
try {
multipartFile.transferTo(file);
fileNames.add(newFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
model.addAttribute("fileNames",fileNames);
return "uploadSuc2";
}
servlet3.0 文件上傳
springmvc中的bean改成
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>
bean里面的屬性只能在web.xml中寫或者使用全注解開發(fā)模式
xml文件
<servlet>
<!--
這里的servlet-name是有講究的,
如果我們不去修改spring配置文件默認(rèn)的位置嗅回,
那么springmvc它會去WEB-INF下面找一個叫做springmvc-servlet.xml的文件
-->
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--可以重命名springmvc的文件名-->
<param-name>namespace</param-name>
<param-value>springmvc-servlet</param-value>
</init-param>
<init-param>
<!--用來制定上下文的位置-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--需要加上這一行-->
<multipart-config>
<max-file-size>200000000</max-file-size>
<max-request-size>2000000000</max-request-size>
</multipart-config>
</servlet>
文件下載
普通方法下載
@RequestMapping("/down2")
public String down2(HttpServletResponse response){
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String filename = "1.jpg";
String downLoadPath = parentPath + filename; //注意不同系統(tǒng)的分隔符
// String downLoadPath =filePath.replaceAll("/", "\\\\\\\\"); //replace replaceAll區(qū)別 *****
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
使用spring自帶的ResponseEntity進(jìn)行下載
@RequestMapping("/down3")
public ResponseEntity<byte[]> export() throws IOException {
String filename = "1.jpg";
HttpHeaders headers = new HttpHeaders();
File file = new File(parentPath + filename);
if(file.exists()){
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", filename);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}else{
System.out.println(filename+" no exists");
return null;
}
}