[File upload] Java files are uploaded locally and displayed by the browser in http mode

In normal development, it is inevitable to encounter the problem of uploading pictures, and when there is no test server, you connect to the front-end interface and find that the picture is not displayed after uploading. It is a disk path: (as shown in the figure below). Through the function implementation under tomact, the code implementation is very simple, and the http path is also returned.

Insert picture description here

Solution: The picture does not display the problem

After registering the ServletContext, when the springboot project is started, a
folder similar to (below) will be generated under C:\Users\MAIBENBEN\AppData\Local\Temp. The generated
Insert picture description here
pictures are in this folder

The path is also printed out in the code.
Insert picture description here
Follow this path to find the storage path of the picture.

The following code implementation

Realization: upload files locally and echo the front end in http

UploadFileController

package xgg.springboot.base.controller;

import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xgg.springboot.common.util.GetIpAddressUtil;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author xiegege
 * @date 2020/12/7 14:03
 */
@Slf4j
@RestController
@RequestMapping("upload")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UploadFileController {
    
    

    private final ServletContext context;

    @PostMapping("upload-image")
    public Map<String, String> upload(MultipartFile file) throws IOException {
    
    
        //参数校验
        if (file == null) {
    
    
            throw new IllegalArgumentException("file or filename object is null");
        }
        // 获取文件类型
        String contentType = file.getContentType();
        // 获取文件后缀
        String ext = contentType.substring(contentType.lastIndexOf("/") + 1);
        // uuid生成文件名 + 后缀
        String fileName = UUID.randomUUID() + "." + ext;
        // 返回url路径
        String url = "http://" + GetIpAddressUtil.getIpAddress() + ":8000/statics/attachment/" + fileName;
        // 本地磁盘存储路径
        String filePath = context.getRealPath("/") + "statics/attachment/" + fileName;
        log.info("入库本地磁盘路径:" + filePath);
        // 写入文件
        write(file.getInputStream(), filePath);
        // 返回数据
        Map<String, String> dataMap = new HashMap<>(3);
        dataMap.put("name", fileName);
        dataMap.put("url", url);
        dataMap.put("ext", ext);
        return dataMap;
    }

    /**
     * 将inputStream写入文件
     *
     * @param stream 文件流
     * @param path   要写入的文件路径
     */
    private static void write(InputStream stream, String path) {
    
    
        try {
    
    
            FileUtils.copyInputStreamToFile(stream, new File(path));
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

GetIpAddressUtil

public class GetIpAddressUtil {
    
    

    public static void main(String[] args) {
    
    
        System.out.println("本机IP:" + getIpAddress());
    }

    public static String getIpAddress() {
    
    
        try {
    
    
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (allNetInterfaces.hasMoreElements()) {
    
    
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
    
    
                    continue;
                } else {
    
    
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
    
    
                        ip = addresses.nextElement();
                        if (ip instanceof Inet4Address) {
    
    
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
    
    
            System.err.println("IP地址获取失败" + e.toString());
        }
        return "";
    }
}

Call interface

Insert picture description here

Access path

Insert picture description here
The picture shows that the 这里的192.168.52.1是我的本机ip
image
front-end echo is also normal. It's done, now you can feel the fish.

Need to pay attention to

项目启动后每次都会生成新的文件夹
Insert picture description here
之前传入的文件就访问不到了,所以在测试一套流程的时候,尽量后端避免重启服务,或者是把之前的图片全部剪切到新生成的文件中。

to sum up

如果觉得不错,可以点赞+收藏或者关注下博主。感谢阅读!

Guess you like

Origin blog.csdn.net/weixin_42825651/article/details/110819263