package com.example.ok.controller.File;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Value("${file.upload.url}")
    private String uploadFilePath;

    @RequestMapping("/upload")
    public String httpUpload(@RequestParam("files") MultipartFile files[]) throws JSONException {
        JSONObject object=new JSONObject();
        for(int i=0;i<files.length;i++){
            String fileName = files[i].getOriginalFilename(); 
            File dest = new File(uploadFilePath +'/'+ fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
            } catch (Exception e) {
                log.error("{}",e);
                object.put("success",2);
                object.put("result","程序错误,请重新上传");
                return object.toString();
            }
        }
        object.put("success",1);
        object.put("result","文件上传成功");
        return object.toString();
    }

}

在application.yml或application.properties中配置文件上传到的目录
#文件上传目录
file.upload.url=路径
记住要有传递的前端html页面:否则报错
<!--multipart/form-data	不对字符编码。当使用有文件上传控件的表单时,该值是必需的。-->
<!--multiple可接受多个值的文件上传字段:-->
<form action="/file/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple="multiple" />
    <button type="submit">上传</button>
</form>

可以实现了 参考自:https://cloud.tencent.com/developer/article/1594124

posted on 2024-09-12 19:32  蒸饺  阅读(16)  评论(0)    收藏  举报