蔡香满屋
站在牛顿头上吃苹果

文件上传:

首先使用前端模板是freemarker:

<form method="post" enctype="multipart/form-data"
action="/file/upload">
	文件:<input type="file" name="cgbFile"><br>
<button type="submit">上传文件</button>
</form>

  

在controller处理代码如下:

package com.cors.example.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file/")
public class FileController {
	@RequestMapping("upload")
     @ResponseBody public String upload(@RequestParam("cgbFile")MultipartFile file) { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 文件上传存放路径 String filePath = "E:/upload/"; // fileName重名情况处理,可使用UUID或者时间 fileName = filePath + UUID.randomUUID() + fileName; File dest = new File(fileName); // 创建文件
          // 判断目录是否存在,没有则创建 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上传成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上传失败"; } }

 通过访问上传文件之后就会返回成功的标志:

于是在E盘的upload这个文件夹下就存在了:

 ----------------

下载文件:

在freemarker模板的html写上:

<a href="/file/download">下载文件</a>

然后实现控制器的代码如下:

    @SuppressWarnings("resource")
	@RequestMapping("download")
	public void download(HttpServletResponse response) throws IOException {
		File file = new File("E:\\upload\\query-2.0.0.min.js"); // 目前写成静态的路径,如果有数据库,查的是数据库的路径
		FileInputStream fis = new FileInputStream(file);
		response.setContentType("application/force-download"); // 设置是下载而不是打开
		// 设置下载的文件名
		response.addHeader("Content-disposition", "attachment;fileName=query-2.0.0.min.js");
		OutputStream os = response.getOutputStream();
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = fis.read(buf)) != -1) {
			os.write(buf, 0, len);
		}
	}

  于是就成功了。

posted on 2019-03-10 19:54  蔡香满屋  阅读(225)  评论(0)    收藏  举报