文件上传和文件下载回显
package com.jing.reggie_takeout.controller;
import com.jing.reggie_takeout.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/common")
public class UploadDownloadController {
@Value("${reggie.path}")
private String basePath;
@PostMa
@PostMapping("/upload")
public Result<String> upload(MultipartFile file){
String originalFilename = file.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
File file1 = new File(basePath);
if (!file1.exists()){
file1.mkdirs();
}
try {
file.transferTo(new File(basePath+"\\"+ fileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
return Result.success(fileName);
}
@GetMapping("/download")
public void download(@RequestParam("name") String fileName, HttpServletResponse response){
String name = basePath+ "\\" + fileName;
FileInputStream fileInputStream = null;
ServletOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(new File(name));
fileOutputStream = response.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1){
fileOutputStream.write(bytes,0,len);
fileOutputStream.flush();
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
server:
port: 8080
spring:
application:
name: reggie_take_out
datasource:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/reggie?useSSL=false&characterEncoding=UTF8&serverTimezone=UTC
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
global-config:
db-config:
id-type: ASSIGN_ID
type-aliases-package: com.jing.reggie_takeout.entity
reggie:
path: H:\java_projects\reggie_takeout\src\main\resources\reggie\img\图片资源
<div>
<el-form-item
label="菜品图片:"
prop="region"
class="uploadImg"
>
<el-upload
class="avatar-uploader"
action="/common/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:on-change="onChange"
ref="upload"
>
<img
v-if="imageUrl"
:src="imageUrl"
class="avatar"
></img>
<i
v-else
class="el-icon-plus avatar-uploader-icon"
></i>
</el-upload>
</el-form-item>
</div>