java spring 文件上传_springmvc文件上传

packagecom.sz.controller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.multipart.MultipartFile;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.HashMap;importjava.util.Map;

@Controller

@RequestMapping("/upload")public classUploadController {//定义文件上传根路径

private String path = "D:" + File.separator + "upload";

@RequestMapping("/m1")

@ResponseBody//使用注解标记上传文件

public Map m1(@RequestParam("file")MultipartFile multipartFile, @RequestParam("name") String name){

System.out.println("普通的文本域:" +name);//如果不为空,再准备上传

Map map = new HashMap<>();int code = 4300;if(!multipartFile.isEmpty()) {

BufferedOutputStream bs= null;try{byte[] bytes =multipartFile.getBytes();//构建文件对象,准备上传

File file= newFile(path );//如果路径海不存在,则创建

if(!file.exists())

file.mkdirs();//获取文件原始名称

String originalFilename =multipartFile.getOriginalFilename();//获取文件前缀(比如hello.txt 取出hello)不含后缀

String prefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));//获取文件后缀名 .txt

String suffix= originalFilename.substring(originalFilename.lastIndexOf("."));//上传后的文件名加上时间戳

String newFileName =prefix+System.currentTimeMillis()+suffix ;//构建文件对象

File uploadFile = new File(path+ File.separator +newFileName);//通过输出流写出

bs = new BufferedOutputStream(newFileOutputStream(uploadFile));

bs.write(bytes);

code= 2000;

}catch(IOException e) {

e.printStackTrace();

}finally{if(bs !=null){try{

bs.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

map.put("msg",code);returnmap;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值