图片上传至本地

1.配置文件

bootstrap.yml
file:
  path:
    httpResURL: http://122.246.1.148:19086
    SAVE_PATH: /data/images
    resURI: /wzq/

2.文件工具类


import cn.hutool.core.io.FileUtil;
import com.vinsuan.park.platform.biz.FilePathConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@AllArgsConstructor
public class FileUtils {

    public static String upload(MultipartFile file, String pkno, String type, String plateNo) {
        LocalDateTime localDateTime = LocalDateTime.now();
        String yyyyMMdd = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String HHmmss = localDateTime.format(DateTimeFormatter.ofPattern("HHmmss"));
        //文件名绑定后缀  pkno_type_plateNo_20191011_143600(车场-进出-车牌-年月日-时分秒)
        String md5File = pkno + "_" + type + "_" + plateNo + "_" + yyyyMMdd + "_" + HHmmss + ".jpg";

        File path = new File(FilePathConfig.savePath + FilePathConfig.resUri);
        if (!path.exists()) {
            path.mkdirs();
        }

        File localFile = new File(FilePathConfig.savePath + FilePathConfig.resUri, md5File);

        if (!FileUtil.exist(localFile)) {
            //创建一个新文件
            File attachFile = FileUtil.touch(FilePathConfig.savePath + FilePathConfig.resUri, md5File);
            //将文件流写入文件中
            try {
                FileUtil.writeFromStream(file.getInputStream(), attachFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return FilePathConfig.httpResUrl + FilePathConfig.resUri + md5File;
    }

    /**
     * 保存文件(此案例中未使用)
     */
    public static File saveFileFromInputStream(InputStream stream, String path, String filename, byte[] buff)
            throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            log.info("++++++++++++++创建文件++++++++++++++++++++++++++++:" + path);
            file.mkdirs();
        }
        FileOutputStream fs = new FileOutputStream(path + filename);
        byte[] buffer = new byte[1024 * 1024];
        int byteread = 0;
        if (null == buff || buff.length <= 0) {
            while ((byteread = stream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
        } else {
            fs.write(buff);
        }
        fs.flush();
        fs.close();
        if (null != stream) {
            stream.close();
        }
        return file;
    }

//    public static void main(String[] args) {
//        String imageStr = Base64Utils.GetImageStr("D:\\Pictures\\yy.jpg");
//        MultipartFile file = Base64ToMultipartFile.base64ToMultipart(imageStr);
//        String upload = FileUtils.upload(file, "cc8888", "1", "浙B88888");
//        System.out.println(upload);
//    }
}

3.图片转图片BASE64值
4.图片BASE64转MultipartFile
注意:
1.图片存储路径为当前项目盘\data\images\wzq
2.此文件工具栏返回的图片是路径是:http://122.246.1.148:19999/wzq/20191022114711.jpg,不是:http://122.246.1.148:19999/data/images/20191022114711.jpg,是因为访问路径有做映射。wzq->data/images

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
以下是Java代码将文件上传至本地的示例: ```java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/upload") @MultipartConfig public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String UPLOAD_DIR = "uploads"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String applicationPath = request.getServletContext().getRealPath(""); String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; File fileUploadDirectory = new File(uploadFilePath); if (!fileUploadDirectory.exists()) { fileUploadDirectory.mkdirs(); } Part filePart = request.getPart("file"); String fileName = getFileName(filePart); String savePath = uploadFilePath + File.separator + fileName; InputStream inputStream = filePart.getInputStream(); Path filePath = Paths.get(savePath); Files.copy(inputStream, filePath); response.getWriter().println("File " + fileName + " has been uploaded successfully!"); } private String getFileName(final Part part) { final String partHeader = part.getHeader("content-disposition"); for (String content : partHeader.split(";")) { if (content.trim().startsWith("filename")) { return content.substring(content.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } } ``` 解释: - `@WebServlet("/upload")` 注释指定了上传文件的路径。 - `@MultipartConfig` 注释指定了此 Servlet 支持多部分表单数据。 - `doPost()` 方法从请求中获取上传的文件并将其保存到指定的目录中。 - `getFileName()` 方法从请求头中获取文件名。 上传表单可以使用以下 HTML: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>File Upload Form</title> </head> <body> <form method="post" action="upload" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> </body> </html> ``` 此代码将上传的文件保存到 Web 应用程序目录的 `uploads` 文件夹中。可以根据需要更改上传文件的目录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值