欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java 文件上传界面 - 2. Java 多文件上传界面

最编程 2024-06-23 11:17:31
...
import com.newtouch.dangjian.baseapi.util.Info;
import com.newtouch.dangjian.party.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description
 * @Author lph
 * @Date 2020-05-03
 * @Version V1.0
 **/
@RestController
@RequestMapping(path = "upfile")
@Slf4j
public class FileUpLoadController {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @PostMapping("/uploads")
    public String upload(MultipartFile[] uploadFiles, HttpServletRequest request) {
        List list = new ArrayList();//存储生成的访问路径
        if (uploadFiles.length > 0) {
            for (int i = 0; i < uploadFiles.length; i++) {
                MultipartFile uploadFile = uploadFiles[i];
                //设置上传文件的位置在该项目目录下的uploadFile文件夹下,并根据上传的文件日期,进行分类保存
                String realPath = request.getSession().getServletContext().getRealPath("uploadFile");
                String format = sdf.format(new Date());
                File folder = new File(realPath + format);
                if (!folder.isDirectory()) {
                    folder.mkdirs();
                }

                String oldName = uploadFile.getOriginalFilename();
                System.out.println("oldName = " + oldName);
                String newName = UUID.randomUUID().toString() + oldName.
                        substring(oldName.lastIndexOf("."), oldName.length());
                System.out.println("newName = " + newName);
                try {
                    //保存文件
                    uploadFile.transferTo(new File(folder, newName));

                    //生成上传文件的访问路径
                    String filePath = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + "/uploadFile" + format + newName;
                    list.add(filePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return list.toString();
        } else if (uploadFiles.length == 0) {
            return "请选择文件8";
        }
        return "上传失败";
    }
    
}

单文件上传接口是本人及同事所写,多文件上传接口的作者是@Author lph

实现文件上传的时候,可以这样做,文件上传单独做成一个接口,返回值是文件路径。然后普通表单做一个接口,文件上传成功后,将文件接口成功返回的路径放到普通表单中,字段是hidden的input。这样提交到普通接口的时候,普通表单字段和文件路径就可以一并写入到数据库中了。

注:第一段亲测有效,可以将入参改为数组类型,这样就变成了多文件上传,那个Msg是自定义的通用返回类;第二段是朋友写的,小伙伴们可以测试一下,本人还未测试。

推荐阅读