首页 / JAVA / javaWeb文件上传和下载
javaWeb文件上传和下载
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javaWeb文件上传和下载,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4742字,纯文字阅读大概需要7分钟。
内容图文
![javaWeb文件上传和下载](/upload/InfoBanner/zyjiaocheng/640/68a69e62926347e6ae3da07546bb9794.jpg)
第一步
- 先新建一个com.aaa.util包
- 在包里新建一个FileUtil工具类(包括上传和下载方法)
public class FileUtil {
/**
* 通用上传方法
* @param savePath
* @param multipartFile
* @return
*/
public static String uploadFile(String savePath, MultipartFile multipartFile){
String originalFilename = multipartFile.getOriginalFilename();
//获取源文件后缀
String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
//拼装新文件名称
String newFileName= UUID.randomUUID()+suffix;//UUID.randomUUID()随机字符串
File file=new File(savePath+ newFileName);// D:/images/jin.jpg
try {
//调用spring提供的方法进行文件读写
multipartFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
return newFileName;
}
/**
* 通用下载方法
* @param filename
* @param response
* @return
*/
public static String downLoad(String filename,HttpServletResponse response){
String filePath = "D:/images" ;
File file = new File(filePath + "/" + filename);
if(file.exists()){ //判断文件父目录是否存在
response.setContentType("application/force-download");//MIME类型
response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
/* int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}*/
int i=0;
while((i = bis.read(buffer))!=-1){
os.write(buffer,0,i);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------file download" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
controller层代码
@Controller
@RequestMapping("news")
public class NewsController {
@Autowired
private NewsService newsService;
private final ResourceLoader resourceLoader;
@Autowired
public NewsController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
//取出配置文件upload.path的值,赋给uploadPath类变量
@Value(value = "${upload.path}")
private String uploadPath;
/**
* 跳转添加
* @return
*/
@RequestMapping("toAdd")
public String toAdd(){
return "add";
}
@RequestMapping("add")
public String add(Model model,@RequestParam Map map, @RequestParam MultipartFile pic){
if(pic!=null){
String newFilePath= FileUtil.uploadFile(uploadPath,pic);
map.put("fileName",pic.getOriginalFilename());
map.put("picPath",newFilePath);
}
int i=newsService.add(map);
if(i>0){
model.addAttribute("info","图片添加成功");
return "redirect:list";
}else{
model.addAttribute("info","图片添加失败");
return "redirect:list";
}
}
/**
* 新闻列表
* @return
*/
@RequestMapping("list")
public String list(Model model){
model.addAttribute("newsList",newsService.getList());
return "list";
}
/**
* 新闻删除
*/
@RequestMapping("delete")
public Object delete(Integer id){
newsService.delete(id);
return "forward:list";
}
/**
* 新闻修改
*/
@RequestMapping("toUpdate")
public String toUpdate(Model model,Integer id){
List<Map> listById = newsService.getListById(id);
model.addAttribute("list",listById);
return "edit";
}
@RequestMapping("update")
public Object update(@RequestParam Map map,@RequestParam MultipartFile pic){
System.out.println(map);
String originalFilename = pic.getOriginalFilename();
String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
String newFileName=UUID.randomUUID()+suffix;
File file=new File(uploadPath+newFileName);
try {
pic.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
map.put("picPath",newFileName);
newsService.update(map);
return "forward:list";
}
@RequestMapping("show")
public ResponseEntity show(String fileName){
try {
// 由于是读取本机的文件,file是一定要加上的, path是在application配置文件中的路径
return ResponseEntity.ok(resourceLoader.getResource("file:" + uploadPath + fileName));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
/**
* 文件下载
* @param fileName
* @param response
*/
@RequestMapping("/downLoad")
public void downLoadFile(String fileName, HttpServletResponse response){
FileUtil.downLoad(fileName,response);
}
}
dao层代码
public interface NewsDao {
/**
* 获取新闻列表
* @return
*/
@Select(value = "select * from tb_news")
List<Map> getList();
/**
* 新闻添加
* @param map
* @return
*/
@Insert(value = "insert into tb_news values(seq_news_id.nextval,#{title},#{content},#{type},0,#{picPath})")
int add(Map map);
/**
* 新闻删除
*/
@Delete(value = "delete from tb_news where newsid=#{newsid}")
int delete(int id);
/**
* 根据id获取新闻信息
*/
@Select(value = "select * from tb_news where newsid=#{newsid}")
List<Map> getListById(int id);
/**
* 更改新闻信息
*/
@Update(value = "update tb_news set title=#{title},content=#{content},typeid=#{typeid},picpath=#{picPath} where newsid=#{newsid}")
int update(Map map);
}
内容总结
以上是互联网集市为您收集整理的javaWeb文件上传和下载全部内容,希望文章能够帮你解决javaWeb文件上传和下载所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。