Java 多文件上传(transferTo)


1.在application.properties中配置文件路径

file.upload.url:E:/test/upload/file

2.文件上传代码

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
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;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("file")
public class UploadController {


    @ApiOperation(value="多文件上传")

    @PostMapping( value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Object upload(@RequestParam("file") MultipartFile[] file){
        Map<String,Object> map = new HashMap<>();
        map.put("status",200);
        List<Map<String,Object>> result = new ArrayList<>();
        if(!ObjectUtils.isEmpty(file) && file.length>0){
            Arrays.asList(file).stream().forEach(files->result.add(singleFileUpload(files)));
        }
        map.put("data",result);
        return map;
    }

    //获取配置路径
    @Value("${file.upload.url}")
    private String uploadFilePath;

    private Map<String, Object> singleFileUpload(MultipartFile files) {
        Map<String,Object> map = new HashMap<>();
        //防止因文件名重复导致文件丢失
        String path = new String(uploadFilePath+"_"+UUID.randomUUID().toString().replace("-","").toLowerCase());
        //文件路径
        File dest =new File(path+File.separator+ files.getOriginalFilename());
        if(!dest.getParentFile().exists()){
            //避免文件创建失败,如果文件夹不存在,则创建
            dest.getParentFile().mkdirs();
        }
        try {
            files.transferTo(dest);
            map.put("url",dest);
            map.put("fileName",files.getOriginalFilename());
            map.put("success",1);
            map.put("result","文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            map.put("success",2);
            map.put("result","文件上传失败");
        }
        return map;
     //返回文件名乱码问题
        //HttpHeaders headers = new HttpHeaders();
        //MediaType mediaType = new MediaType("text","html", Charset.forName("utf-8"));
        //headers.setContentType(mediaType);
     //return new ResponseEntity<String>(js,headers, HttpStatus.OK);
} }

3.postman测试

4.文件保存地址

   final:不积跬步,无以至千里.不积小流,无以成江海


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM