
package Controller;
import jdk.internal.loader.FileURLMapper;
import org.apache.commons.io.FileUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@Controller
@RequestMapping("/file")
public class FileHandler {
@RequestMapping("/upload")
public String upload(MultipartFile img, HttpServletRequest request) {
if (img.getSize() > 0) {
//获取保存上传文件的file路径
String path = request.getServletContext().getRealPath("file");
//获取上传的文件名
String name = img.getOriginalFilename();
String filePath = "D:\Work\Java\SpringMVC\src\main\webapp";
File file = new File(filePath, name);
try {
img.transferTo(file);
//保存上传之后的文件路径
request.setAttribute("path", filePath + "\" + name);
} catch (IOException e) {
e.printStackTrace();
}
}
return "upload";
}
@GetMapping("/download/{name}")
public void download(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response) {
if(name != null) {
name += ".png";
String path = request.getServletContext().getRealPath("file");
File file = new File(path, name);
OutputStream outputStream = null;
if(file.exists()) {
response.setContentType("application/forc-download");
response.setHeader("Content-Disposition", "attachment;filename="+name);
try {
outputStream = response.getOutputStream();
outputStream.write(FileUtils.readFileToByteArray(file));
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)