springboot图片上传与浏览器展示
程序员文章站
2022-06-28 16:35:45
package com.demo.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.io.Resource;import org.springframework.core.io.ResourceLoader;import org.springframework.http.MediaType;import org.springframewo...
package com.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author admin
*/
@RestController
public class UploadController {
/**上传文件
* @param username
* @param inputfile. MultipartFile变量的名字需要与上传文件时的name保持一致 .<input type="file" name="inputfile">
* @return
* @throws IOException
*/
@PostMapping("/uploadfile")
public String uploadFile(String username, MultipartFile inputfile) throws IOException {
String originalFilename = inputfile.getOriginalFilename();
String sub = originalFilename.split("\\.")[1];
String subname;
if (!username.equals("")) {
subname = username.concat("." + sub);
} else {
subname = originalFilename;
}
System.out.println(subname);
System.out.println(originalFilename);
System.out.println(inputfile.getName());
inputfile.transferTo(new File("E:/文件/" + subname));
return "上传成功";
}
@Autowired
private ResourceLoader resourceLoader;
// 浏览器显示图片
@GetMapping("/getImg/{imgname:.+}")
public ResponseEntity getImg(@PathVariable String imgname) {
System.out.println(imgname);
Path path = Paths.get("F:\\文件", imgname);
System.out.println(path);
Resource resource = resourceLoader.getResource("file:" + path.toString());
//默认springb 2.x,ResponseEntity.ok(resource) 在浏览器显示为流文件,添加contentType返回指定类型. 1.x直接返回即可
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(resource);
}
}
上传页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片上传</title>
</head>
<body>
<form action="/uploadfile" method="post" enctype="multipart/form-data">
<span>文件名<input type="text" name="username" ></span>
<input type="file" name="inputfile">
<input type="submit" value="上传">
</form>
</body>
</html>
本文地址:https://blog.csdn.net/weixin_42248522/article/details/109628882