欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringMVC中MultipartFile轉(zhuǎn)File的兩種方式

 更新時間:2022年04月08日 10:15:17   作者:扯吧  
在spring上傳文件中,一般都使用了MultipartFile來接收,但是有需要用到File的地方,本文主要介紹了SpringMVC中MultipartFile轉(zhuǎn)File的兩種方式,感興趣的可以了解一下

在spring上傳文件中,一般都使用了MultipartFile來接收,但是有需要用到File的地方,這里只介紹兩種轉(zhuǎn)為File的方法,當(dāng)然也有一些其他的方法,我試了有些錯誤,所以就不提了;

  • transferTo()
  • org.apache.commons.io.FileUtils.copyInputStreamToFile()

代碼如下:

public void upload(@RequestParam(value = "file") MultipartFile file) {
?? ??? ?if (file != null) {?
?? ??? ??? ?try {
?? ??? ??? ??? ?String fileRealName = file.getOriginalFilename();//獲得原始文件名;?
?? ??? ??? ??? ?int pointIndex = ?fileRealName.lastIndexOf(".");//點號的位置 ? ??
?? ??? ??? ??? ?String fileSuffix = fileRealName.substring(pointIndex);//截取文件后綴 ?
?? ??? ??? ??? ?String fileNewName = DateUtils.getNowTimeForUpload();//新文件名,時間戳形式y(tǒng)yyyMMddHHmmssSSS
?? ??? ??? ??? ?String saveFileName = fileNewName.concat(fileSuffix);//新文件完整名(含后綴)?
?? ??? ??? ??? ?String filePath ?= "D:\\FileAll" ;
?? ??? ??? ??? ?File path = new File(filePath); //判斷文件路徑下的文件夾是否存在,不存在則創(chuàng)建
?? ??? ? ? ? ? ?if (!path.exists()) {
?? ??? ? ? ? ? ??? ?path.mkdirs();
?? ??? ? ? ? ? ?}?? ??? ??? ?
?? ??? ? ? ? ? ?File savedFile = new File(filePath);
?? ??? ??? ??? ?boolean isCreateSuccess = savedFile.createNewFile(); // 是否創(chuàng)建文件成功
?? ??? ??? ??? ?if(isCreateSuccess){ ? ? ?//將文件寫入 ? ? ?
?? ??? ??? ??? ??? ?//第一種 ? ? ? ? ? ??
?? ??? ??? ??? ??? ?file.transferTo(savedFile);?
?? ??? ??? ??? ??? ? //第二種
?? ??? ??? ??? ??? ?savedFile = new File(filePath,saveFileName);
?? ??? ??? ??? ??? ?// 使用下面的jar包
?? ??? ??? ??? ??? ?FileUtils.copyInputStreamToFile(file.getInputStream(),savedFile);
?? ??? ??? ??? ?} ??? ??? ??? ??? ??? ??? ??? ?
?? ??? ??? ?} catch (Exception e) {
?? ??? ??? ??? ?e.printStackTrace();?? ??? ??? ??? ?
?? ??? ??? ?}
?? ??? ?}else {
?? ??? ??? ?System.out.println("文件是空的");
?? ??? ?}
?? ?}

附commons-io jar包maven地址:點擊下載 commons-io-2.4.jar

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
</dependency>

到此這篇關(guān)于SpringMVC中MultipartFile轉(zhuǎn)File的兩種方式的文章就介紹到這了,更多相關(guān)SpringMVC MultipartFile轉(zhuǎn)File內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論