Springboot处理文件上传

Maven

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>

可单个文件上传,也可以批量上传


import com.cslg.finalab.beans.JsonData;
import com.cslg.finalab.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value = "/upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @ResponseBody
    @RequestMapping(value = "/image/project")
    public JsonData project(@RequestParam("image") MultipartFile file) {
        uploadService.uploadProjectImage(file);
        return JsonData.success();
    }
    
    @ResponseBody
    @RequestMapping(value = "/image/projectBatch")
    public JsonData projectBatch(@RequestParam("images") MultipartFile[] file) {
        uploadService.batchUploadProjectImage(file);
        return JsonData.success();
    }

    /**
     * 单个上传通过HttpServletRequest获取文件资源
     */
    @ResponseBody
    @RequestMapping(value = "/image/project")
    public JsonData project(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("image");
        uploadService.uploadMemberImage(file);
        return JsonData.success();
    }

    /**
     * 批量上传通过HttpServletRequest获取文件资源
     */
    @ResponseBody
    @RequestMapping(value = "/image/projectBatch")
    public JsonData projectBatch(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("images");
        uploadService.batchUploadMemoryImage(fileList);
        return JsonData.success();
    }
}

service

import com.google.common.collect.Sets;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class UploadServiceImpl implements UploadService {

    private File createFile(String pathName) {
        File file = new File(pathName);
        if(!file.getParentFile().exists()) {
            if(!file.getParentFile().mkdirs()) {
                throw new UploadException(UploadEnum.CREATE_FILE_FAILED);
            }
        }
        if(!file.exists()) {
            try {
                if(file.createNewFile()) {
                    return file;
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new UploadException(UploadEnum.CREATE_FILE_FAILED);
            }
        }
        return file;
    }
    
    private void writeToFile(String pathName, MultipartFile multipartFile) {
        File file = createFile(pathName);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new UploadException(UploadEnum.SERVER_BUSY);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadProjectImage(MultipartFile multipartFile) {
        // 获取上传的文件名称
        String fileName = multipartFile.getOriginalFilename();
        // 文件路径
        String pathName =  "/usr/local/test/" + fileName;
        // 创建文件夹和文件,写入文件
        writeToFile(pathName, multipartFile);
    }

	@Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUploadProjectImage(MultipartFile[] multipartFiles) {
		// 同单个文件处理
    }
   
}

前端上传代码

<form action="http://127.0.0.1:8083/upload/image/project" method="post" enctype="multipart/form-data" name="upload_form">
    <label>选择文件label>
    <input name="image" type="file" />
    <input name="upload" type="submit" value="上传" />
form>

<form method="POST" enctype="multipart/form-data"
      action="http://127.0.0.1:8083/upload/image/projectBatch">
    <p>
        文件1:<input type="file" name="images"/>
    p>
    <p>
        文件2:<input type="file" name="images"/>
    p>
    <p>
        <input type="submit" value="上传"/>
    p>
form>

你可能感兴趣的:(Java)