java kfs_springMVC文件上传

package com.zhiyou100.kfs.controller;

import java.io.File;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.ModelAndView;

import com.zhiyou100.kfs.bean.User;

@Controller

@RequestMapping("user")

public class UserController {

@RequestMapping("upload")

public String upload(ModelAndView mv,User user,MultipartFile[] myfile,HttpServletRequest request) {

mv.setViewName("tes");

//1.通过request获取文件真实上传路径

String pathname=request.getServletContext().getRealPath("/photo");

System.out.println(pathname);

//2.通过真实路径创建文件

File file=new File(pathname);

if(!file.exists()) {//判断是否存在,若不存在则新建

file.mkdirs();

}

for(MultipartFile f:myfile) {

if(f.getSize()>0) {

//3.通过MultipartFile对象获取文件名

String fileName=f.getOriginalFilename();

user.setPhone(fileName);

System.out.println(user);

File targetFile=new File(pathname+"/"+fileName);

try {

//4.保存文件到目标目录

f.transferTo(targetFile);

//4.通过FileUtils把MultipartFile的文件复制到目标文件

//                                 FileUtils.writeByteArrayToFile(targetFile, f.getBytes());

} catch (IOException e) {

e.printStackTrace();

}

}

}

return "index:"+user.getUserId();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值