1. 程式人生 > >springmvc實現上傳和下載

springmvc實現上傳和下載

transfer try .com print frame row 快捷鍵 oid inpu

非常簡單的小例子,註釋的很清楚。話不多少,看代碼

FileController.java
技術分享圖片
package com.imooc;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.InputStream;
import java.io.OutputStream; import java.util.Date; /** * Created by 敲代碼的卡卡羅特 * on 2018/4/15 16:52. */ @RequestMapping("/file") @Controller public class FileController { private String folder="E://update"; @PostMapping public void upload(MultipartFile file) throws Exception { System.out.println(file.getName());
//file 就是你前臺傳過來的參數名字 System.out.println(file.getOriginalFilename()); //idea快捷鍵.txt 就是你文件的實際名字 System.out.println(file.getSize()); //文件的大小 //這裏只是一個小demo,按理說應該截取傳過來的後綴的,這裏寫死了。 File localFile = new File(folder, new Date().getTime() + ".txt"); //復制到這個文件中 file.transferTo(localFile); } @GetMapping("/{id}") public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception { //這個是jdk1.7的新用法,把流寫在try的括號裏面,就不用最後關閉流了。幫你做了 try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt")); OutputStream outputStream = response.getOutputStream();) { //設置信息頭 response.setContentType("application/x-download"); response.addHeader("Content-Disposition", "attachment;filename=test.txt");//filename 就是你下載到本地的名字 //意思是把輸入流復制到輸出流中 IOUtils.copy(inputStream, outputStream); outputStream.flush(); } } }
View Code

依賴看引入的包。就不寫了。

springmvc實現上傳和下載