package com.zouch.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @ClassName FileController
* @Description TODO
* @Author Zouch
* @Date 2020/3/9 16:04
*/
@RequestMapping("/file")
@RestController
public class FileController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file){
if(file.isEmpty()){ //若文件选择为空,就上传失败
return "上传失败,请选择文件!";
}
String fileName=file.getOriginalFilename();//获取文件上传的文件名
String filePath = "F:/fileSource/pic"; //指定到上传的文件路径
File dir = new File(filePath);
if (!dir.exists()) { //若路径不存在,则创建一个这样的文件夹
dir.mkdir();
}
try {
File papers = new File(filePath, fileName); //创建了一个File对象,名字是papers ,路径是filePath,名字是fileName。
//然后就可以调用这个对象的相关方法完成文件创建,删除,读取,写入等操作
file.transferTo(papers); //将上传的文件写入创建好的文件中
return ("上传成功!文件路径为:"+filePath+"/"+fileName);
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败!";
}
}
JAVA上传图片
猜你喜欢
转载自blog.csdn.net/woshizouqi/article/details/104759423
今日推荐
周排行