最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解決MultipartFile.transferTo(dest) 報(bào)FileNotFoundExcep的問(wèn)題

 更新時(shí)間:2021年07月01日 10:47:13   作者:dany_zj_cn  
這篇文章主要介紹了解決MultipartFile.transferTo(dest) 報(bào)FileNotFoundExcep的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Spring Upload file 報(bào)錯(cuò)FileNotFoundException

環(huán)境:

  • Springboot 2.0.4
  • JDK8
  • 內(nèi)嵌 Apache Tomcat/8.5.32

表單,enctype 和 input 的type=file 即可,例子使用單文件上傳

<form enctype="multipart/form-data" method="POST"
 action="/file/fileUpload">
 圖片<input type="file" name="file" />
 <input type="submit" value="上傳" />
</form>
@Controller
@RequestMapping("/file")
public class UploadFileController {
	@Value("${file.upload.path}")
	private String path = "upload/";

	@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
	@ResponseBody
	public String fileUpload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return "false";
		}
		String fileName = file.getOriginalFilename();
		File dest = new File(path + "/" + fileName);
		if (!dest.getParentFile().exists()) { 
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest); // 保存文件
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
	}
}

運(yùn)行在保存文件 file.transferTo(dest) 報(bào)錯(cuò)

問(wèn)題

dest 是相對(duì)路徑,指向 upload/doc20170816162034_001.jpg

file.transferTo 方法調(diào)用時(shí),判斷如果是相對(duì)路徑,則使用temp目錄,為父目錄

因此,實(shí)際保存位置為 C:\Users\xxxx\AppData\Local\Temp\tomcat.372873030384525225.8080\work\Tomcat\localhost\ROOT\upload\doc20170816162034_001.jpg

一則,位置不對(duì),二則沒(méi)有父目錄存在,因此產(chǎn)生上述錯(cuò)誤。

解決辦法

transferTo 傳入?yún)?shù) 定義為絕對(duì)路徑

@Controller
@RequestMapping("/file")
public class UploadFileController {
	@Value("${file.upload.path}")
	private String path = "upload/";

	@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
	@ResponseBody
	public String fileUpload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return "false";
		}
		String fileName = file.getOriginalFilename();
		File dest = new File(new File(path).getAbsolutePath()+ "/" + fileName);
		if (!dest.getParentFile().exists()) { 
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest); // 保存文件
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
	}
}

另外也可以 file.getBytes() 獲得字節(jié)數(shù)組,OutputStream.write(byte[] bytes)自己寫(xiě)到輸出流中。

補(bǔ)充方法

application.properties 中增加配置項(xiàng)

spring.servlet.multipart.location= # Intermediate location of uploaded files.

關(guān)于上傳文件的訪(fǎng)問(wèn)

1、增加一個(gè)自定義的ResourceHandler把目錄公布出去

// 寫(xiě)一個(gè)Java Config 
@Configuration
public class webMvcConfig implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer{
	// 定義在application.properties
	@Value("${file.upload.path}")
	private String path = "upload/";
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String p = new File(path).getAbsolutePath() + File.separator;//取得在服務(wù)器中的絕對(duì)路徑
		System.out.println("Mapping /upload/** from " + p);
		registry.addResourceHandler("/upload/**") // 外部訪(fǎng)問(wèn)地址
			.addResourceLocations("file:" + p)// springboot需要增加file協(xié)議前綴
			.setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// 設(shè)置瀏覽器緩存30分鐘
	}
}

application.properties 中 file.upload.path=upload/

實(shí)際存儲(chǔ)目錄

D:/upload/2019/03081625111.jpg

訪(fǎng)問(wèn)地址(假設(shè)應(yīng)用發(fā)布在http://www.a.com/)

http://www.a.com/upload/2019/03081625111.jpg

2、在Controller中增加一個(gè)RequestMapping,把文件輸出到輸出流中

@RestController
@RequestMapping("/file")
public class UploadFileController {
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;
	@Autowired
	protected ConversionService conversionService;

	@Value("${file.upload.path}")
	private String path = "upload/";	

	@RequestMapping(value="/view", method = RequestMethod.GET)
	public Object view(@RequestParam("id") Integer id){
		// 通常上傳的文件會(huì)有一個(gè)數(shù)據(jù)表來(lái)存儲(chǔ),這里返回的id是記錄id
		UploadFile file = conversionService.convert(id, UploadFile.class);// 這步也可以寫(xiě)在請(qǐng)求參數(shù)中
		if(file==null){
			throw new RuntimeException("沒(méi)有文件");
		}
		
		File source= new File(new File(path).getAbsolutePath()+ "/" + file.getPath());
		response.setContentType(contentType);

		try {
			FileCopyUtils.copy(new FileInputStream(source), response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

MultipartFile.transferTo(dest) 報(bào)找不到文件

今天使用transferTo這個(gè)方法進(jìn)行上傳文件的使用發(fā)現(xiàn)了一些路徑的一些問(wèn)題,查找了一下記錄問(wèn)題所在

前端上傳網(wǎng)頁(yè),使用的是單文件上傳的方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
    <form enctype="multipart/form-data" method="post" action="/upload">
        文件:<input type="file" name="head_img">
        姓名:<input type="text" name="name">
        <input type="submit" value="上傳">
    </form>
</body>
</html>

后臺(tái)網(wǎng)頁(yè)

@Controller
@RequestMapping("/file")
public class UploadFileController {
    @Value("${file.upload.path}")
    private String path = "upload/";
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { 
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
}

這個(gè)確實(shí)存在一些問(wèn)題

路徑是不對(duì)的

dest 是相對(duì)路徑,指向 upload/doc20170816162034_001.jpg

file.transferTo 方法調(diào)用時(shí),判斷如果是相對(duì)路徑,則使用temp目錄,為父目錄

因此,實(shí)際保存位置為 C:\Users\xxxx\AppData\Local\Temp\tomcat.372873030384525225.8080\work\Tomcat\localhost\ROOT\upload\doc20170816162034_001.jpg

所以改為:

@Controller
@RequestMapping("/file")
public class UploadFileController {
    @Value("${file.upload.path}")
    private String path = "upload/";
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(new File(path).getAbsolutePath()+ "/" + fileName);
        if (!dest.getParentFile().exists()) { 
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • MyBatis入門(mén)介紹(超簡(jiǎn)單)

    MyBatis入門(mén)介紹(超簡(jiǎn)單)

    mybatis是Java的持久層框架, JAVA操作數(shù)據(jù)庫(kù)是通過(guò)jdbc來(lái)操作的,而mybatis是對(duì)jdbc的封裝。下文給大家介紹mybatis入門(mén)知識(shí),感興趣的朋友參考下吧
    2017-08-08
  • springboot實(shí)現(xiàn)圖片大小壓縮功能

    springboot實(shí)現(xiàn)圖片大小壓縮功能

    這篇文章主要為大家詳細(xì)介紹了springboot實(shí)現(xiàn)圖片大小壓縮功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • Maven工程搭建spring boot+spring mvc+JPA的示例

    Maven工程搭建spring boot+spring mvc+JPA的示例

    本篇文章主要介紹了Maven工程搭建spring boot+spring mvc+JPA的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-01-01
  • Java設(shè)計(jì)模式之中介模式(Mediator模式)介紹

    Java設(shè)計(jì)模式之中介模式(Mediator模式)介紹

    這篇文章主要介紹了Java設(shè)計(jì)模式之中介模式(Mediator模式)介紹,本文講解了為何使用Mediator模式、如何使用中介模式等內(nèi)容,需要的朋友可以參考下
    2015-03-03
  • Java的Netty進(jìn)階之Future和Promise詳解

    Java的Netty進(jìn)階之Future和Promise詳解

    這篇文章主要介紹了Java的Netty進(jìn)階之Future和Promise詳解,Netty 是基于 Java NIO 的異步事件驅(qū)動(dòng)的網(wǎng)絡(luò)應(yīng)用框架,使用 Netty 可以快速開(kāi)發(fā)網(wǎng)絡(luò)應(yīng)用,Netty 提供了高層次的抽象來(lái)簡(jiǎn)化 TCP 和 UDP 服務(wù)器的編程,但是你仍然可以使用底層的 API,需要的朋友可以參考下
    2023-11-11
  • SpringBoot中使用configtree讀取樹(shù)形文件目錄中的配置詳解

    SpringBoot中使用configtree讀取樹(shù)形文件目錄中的配置詳解

    這篇文章主要介紹了SpringBoot中使用configtree讀取樹(shù)形文件目錄中的配置詳解,configtree通過(guò)spring.config.import?+?configtree:前綴的方式,加載以文件名為key、文件內(nèi)容為value的配置屬性,需要的朋友可以參考下
    2023-12-12
  • Java根據(jù)前端返回的字段名進(jìn)行查詢(xún)數(shù)據(jù)的實(shí)現(xiàn)方法

    Java根據(jù)前端返回的字段名進(jìn)行查詢(xún)數(shù)據(jù)的實(shí)現(xiàn)方法

    在Java后端開(kāi)發(fā)中,我們經(jīng)常需要根據(jù)前端傳遞的參數(shù)(如字段名)來(lái)動(dòng)態(tài)查詢(xún)數(shù)據(jù)庫(kù)中的數(shù)據(jù),這種需求通常出現(xiàn)在需要實(shí)現(xiàn)通用查詢(xún)功能或者復(fù)雜查詢(xún)接口的場(chǎng)景中,所以本文介紹了Java根據(jù)前端返回的字段名進(jìn)行查詢(xún)數(shù)據(jù)的實(shí)現(xiàn)方法,需要的朋友可以參考下
    2024-12-12
  • struts2獲取服務(wù)器臨時(shí)目錄的方法

    struts2獲取服務(wù)器臨時(shí)目錄的方法

    這篇文章主要為大家詳細(xì)介紹了struts2獲取服務(wù)器臨時(shí)目錄的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • RabbitMQ消息有效期與死信的處理過(guò)程

    RabbitMQ消息有效期與死信的處理過(guò)程

    利用DLX,當(dāng)消息在一個(gè)隊(duì)列中變成死信?(dead?message)?之后,它能被重新publish到另一個(gè)Exchange,這個(gè)Exchange就是DLX,本文重點(diǎn)給大家介紹RabbitMQ消息有效期與死信的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧
    2022-03-03
  • spring IOC中三種依賴(lài)注入方式

    spring IOC中三種依賴(lài)注入方式

    這篇文章主要介紹了spring IOC中三種依賴(lài)注入方式,Spring使用注入方式,為什么使用注入方式,這系列問(wèn)題實(shí)際歸結(jié)起來(lái)就是一句話(huà),Spring的注入和IoC(本人關(guān)于IoC的闡述)反轉(zhuǎn)控制是一回事
    2021-08-08

最新評(píng)論

栾城县| 通海县| 灵山县| 翼城县| 大田县| 中牟县| 嘉荫县| 肃南| 织金县| 衢州市| 嵩明县| 高要市| 临猗县| 福州市| 湟源县| 哈尔滨市| 资源县| 阿巴嘎旗| 苏尼特右旗| 牙克石市| 永新县| 和硕县| 平阴县| 凉城县| 罗源县| 浑源县| 中山市| 淅川县| 青岛市| 西平县| 威信县| 苍梧县| 阳城县| 乐昌市| 洛川县| 林甸县| 万全县| 通江县| 阜康市| 乌鲁木齐市| 武安市|