MultipartFile中transferTo(Filefile)的路径问题及解决transferTo(File file)的路径问题
今天看到layui的⽂件上传的控件,就尝试了⼀下。简单创建了⼀个SpringMVC项⽬。记得在配置⽂件中注⼊以下Bean。
<!-- 定义⽂件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipartmons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定⽂件上传的最⼤值为5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
<!-- 设定⽂件上传时写⼊内存的最⼤值,如果⼩于这个参数不会⽣成临时⽂件,默认为10240 -->
<property name="maxInMemorySize" value="40960"></property>
<!-- 上传⽂件的临时路径 -->
<property name="uploadTempDir" value="fileUpload/temp"></property>
<!-- 延迟⽂件解析 -->
<property name="resolveLazily" value="true"/>
</bean>
我很懒,这些属性都没有配置,就注册了Bean。
接下来是我出错的地⽅。先上Controller代码,前台通过Layui的⽂件上传模块上传⽂件。
@ResponseBody
@RequestMapping("/upload")
public Map upload(HttpServletRequest request,MultipartFile file){
HashMap<String,String> map=new HashMap();
if (!file.isEmpty()) {
try {
// getOriginalFilename()是包含源⽂件后缀的全名
String filePath = "D:/upload/test/"+OriginalFilename();
System.out.println(filePath);
File saveDir = new File(filePath);
if (!ParentFile().exists())
map.put("res","上传成功");
return map;
} catch (Exception e) {
e.printStackTrace();
}
}
map.put("res","上传失败");
return map;
}
transferTo⽅法中传递的file如果是路径的话,那么它会将最后⼀层路径当做⽂件名,没有后缀的那种。此时重命名这个⽂件,更改成和上传⽂件⼀致的后缀那么就可以打开了。
⽐如我将
String filePath = "D:/upload/test/"+OriginalFilename();
改成
String filePath = "D:/upload/test";
运⾏之后打开⽂件发现这样的:
transferTo将我想作为⽂件夹的test当做⽂件名了。我加个后缀.jpg
和上传的⽂件⼀致。
最后个⼈理解为传⼊的File参数是应该包含⽂件⽽不是⽂件路径,transferTo()并不会将⽂件转存到⽂件夹下。ansferTo( )遇见的问题记录
环境:
Springboot 2.0.4
JDK8
表单,enctype 和 input 的type=file 即可,例⼦使⽤单⽂件上传
<form enctype="multipart/form-data" method="POST"
action="/file/fileUpload">
图⽚<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
1.⽂件上传接值的⼏种⽅式
#spring.servlet.multipart.location=D:/fileupload1
/**
* 使⽤ httpServletRequest作为参数
* @param  httpServletRequest
* @return
*/
@PostMapping("/upload")
@ResponseBody
public Map<String, Object> upload(HttpServletRequest httpServletRequest){
boolean flag = false;
MultipartHttpServletRequest multipartHttpServletRequest = null;
//强制转换为MultipartHttpServletRequest接⼝对象 (它包含所有HttpServletRequest的⽅法)
if(httpServletRequest instanceof MultipartHttpServletRequest){
multipartHttpServletRequest = (MultipartHttpServletRequest) httpServletRequest;
}else{
return dealResultMap(false, "上传失败");
}
//获取MultipartFile⽂件信息(注意参数为前端对应的参数名称)
MultipartFile mf = File("file");
//获取源⽂件名称
String fileName = mf.getOriginalFilename();
/
/存储路径可在配置⽂件中指定
File pfile = new File("D:/fileupload1/");
if (!ists()) {
pfile.mkdirs();
}
File file = new File(pfile,  fileName);
/* //指定好存储路径
File file = new File(fileName);*/
try {
//保存⽂件
//使⽤此⽅法保存必须要绝对路径且⽂件夹必须已存在,否则报错
} catch (IOException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
}
return dealResultMap(true, "上传成功");
}
/**
* 使⽤Spring MVC的multipartFile 类作为参数
*
* @param multipartFile
* @return
*/
@PostMapping("/upload/MultipartFile")
@ResponseBody
public Map<String, Object> uploadMultipartFile(@RequestParam("file") MultipartFile multipartFile){    String fileName = OriginalFilename();
try {
//获取⽂件字节数组
byte [] bytes = Bytes();
//⽂件存储路径(/fileupload1/ 这样会在根⽬录下创建问价夹)
File pfile = new File("/fileupload1/");
//判断⽂件夹是否存在
if(!ists()){
//不存在时,创建⽂件夹
pfile.mkdirs();
}
//创建⽂件
File file = new File(pfile, fileName);
//写⼊指定⽂件夹
OutputStream out = new FileOutputStream(file);
out.write(bytes);
} catch (IOException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
}
/*//如果配置⽂件指定⽬录,就可以直接这样写(不指定路径的,就需要⾃⼰填充保存路径)
File file = new File(fileName);
try {
//使⽤此⽅法保存必须要绝对路径且⽂件夹必须已存在,否则报错
} catch (IOException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
}*/
return dealResultMap(true, "上传成功");
}
@PostMapping("/upload/part")
@ResponseBody
public Map<String, Object> uploadPart(@RequestParam("file") Part part){
System.out.SubmittedFileName());
System.out.Name());
//输⼊流
InputStream inputStream = null;
try {
inputStream = InputStream();
} catch (IOException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
}
//保存到临时⽂件
//1K的数据缓冲流
byte[] bytes = new byte[1024];
//读取到的数据长度
int len;
//输出的⽂件保存到本地⽂件
File pfile = new File("/fileupload1/");
if (!ists()) {
pfile.mkdirs();
}
File file = new File(pfile, SubmittedFileName());
OutputStream out;
try {
out = new FileOutputStream(file);
//开始读取
while ((len = ad(bytes)) != -1){
out.write(bytes, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
} catch (IOException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
}
/*//配置⽂件配置的有默认上传路径
getsavefilename
//获取提交⽂件的名字
String fileName = SubmittedFileName();
try {
/
/使⽤此⽅法保存必须要绝对路径且⽂件夹必须已存在,否则报错
part.write(fileName);
} catch (IOException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
}*/
return dealResultMap(true, "上传成功");
}
注意:
⼀则,位置不对,⼆则没有⽗⽬录存在,因此产⽣上述错误。
//1.使⽤此⽅法保存必须指定盘符(在系统配置时要配绝对路径);
// 也可以通过 File f = new File(new File(path).getAbsolutePath()+ "/" + fileName); 取得在服务器中的绝对路径保存即可//      ansferTo(f);
//2.使⽤此⽅法保存可相对路径(/var/falcon/)也可绝对路径(D:/var/falcon/)
byte [] bytes = Bytes();
OutputStream out = new FileOutputStream(f);
out.write(bytes);
2.关于上传⽂件的访问
(1).增加⼀个⾃定义的ResourceHandler把⽬录公布出去
// 写⼀个Java Config
@Configuration
public class webMvcConfig implements org.springframework.fig.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;//取得在服务器中的绝对路径
System.out.println("Mapping /upload/** from " + p);
registry.addResourceHandler("/upload/**") // 外部访问地址
.addResourceLocations("file:" + p)// springboot需要增加file协议前缀
.setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// 设置浏览器缓存30分钟
}
}
application.properties 中 file.upload.path=upload/
实际存储⽬录
D:/upload/2019/03081625111.jpg
(2).在Controller中增加⼀个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){
// 通常上传的⽂件会有⼀个数据表来存储,这⾥返回的id是记录id
UploadFile file = vert(id, UploadFile.class);// 这步也可以写在请求参数中        if(file==null){
throw new RuntimeException("没有⽂件");
}
File source= new File(new File(path).getAbsolutePath()+ "/" + Path());
response.setContentType(contentType);
try {
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。