JAVA上传图片

妖精的绣舞 提交于 2020-03-10 09:42:33
package com.zouch.controller;

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;

/**
 * @ClassName FileController
 * @Description TODO
 * @Author Zouch
 * @Date 2020/3/9 16:04
 */
@RequestMapping("/file")
@RestController
public class FileController {

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file){
        if(file.isEmpty()){ //若文件选择为空,就上传失败
            return "上传失败,请选择文件!";
        }
        String fileName=file.getOriginalFilename();//获取文件上传的文件名
        String filePath = "F:/fileSource/pic"; //指定到上传的文件路径
        File dir = new File(filePath);
        if (!dir.exists()) {  //若路径不存在,则创建一个这样的文件夹
            dir.mkdir();
        }
        try {
            File papers = new File(filePath, fileName); //创建了一个File对象,名字是papers ,路径是filePath,名字是fileName。
//然后就可以调用这个对象的相关方法完成文件创建,删除,读取,写入等操作
            file.transferTo(papers);    //将上传的文件写入创建好的文件中
            return ("上传成功!文件路径为:"+filePath+"/"+fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败!";
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!