1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.IOException; import java.util.UUID;
@RestController @RequestMapping(path = "/file") public class FileController {
static final String PATH = "D:\\picture";
@RequestMapping(path = "/fileUpload")
public String fileUpload(MultipartFile file) {
String newFileName = "";
String uuid = UUID.randomUUID().toString();
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
File realPathFolder = new File(PATH);
if (!realPathFolder.exists()) { realPathFolder.mkdirs(); }
newFileName = uuid + suffix;
File newFile = new File(realPathFolder, newFileName);
try { file.transferTo(newFile); } catch (IOException e) { System.out.println("上传文件失败!" + e); } return "localhost:8080/files/" + newFileName; } }
|