fangyuan
2022-11-21 5cba031b4fcc437568a46295739fda3dae7ae41f
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.ycl.controller;
 
import com.ycl.api.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
 
@RestController
@RequestMapping("upload")
@Api(tags = "图片上传")
public class ImageUploadController {
    @ApiOperation(value="/image", notes = "上传图片")
    @RequestMapping(value = "/image", method = RequestMethod.POST)
    public CommonResult uploadImage(HttpServletRequest request, MultipartFile image) throws IOException {
 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
 
        String filePath = "/images/" + sdf.format(new Date());
        String imageFolderPath = request.getServletContext().getRealPath(filePath);
        File imageFolder = new File(imageFolderPath);
        if (!imageFolder.exists()) {
            imageFolder.mkdirs();
        }
 
        StringBuilder imageUrl= new StringBuilder();
        imageUrl.append(request.getScheme())
                .append("://")
                .append(request.getServerName())
                .append(":")
                .append(request.getServerPort())
                .append(request.getContextPath())
                .append(filePath);
 
        String imageName = UUID.randomUUID() + "_" + image.getOriginalFilename().replaceAll(" ", "");
        try {
            IOUtils.write(image.getBytes(), new FileOutputStream(new File(imageFolder, imageName)));
            imageUrl.append("/").append(imageName);
            return CommonResult.success(imageUrl.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.failed( "上传失败!");
    }
}