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