java 文件上传

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.owinfo.LnkSign.util;

import com.alibaba.fastjson.JSONObject;
import com.owinfo.utils.basetools.OwinfoResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈简述〉上传原始文件.
 *
 * @author HHYang
 * @version [版本号, 2018年07月30日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */

@Component
public class FileUploadUtil {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FileHelper fileHelper;

    /**
     * 功能简述: 支持多文件上传
     * OwinfoResultUtil 为自定义返回类型,自行修改
     *
     * @param request
     * @return
     * @methodName
     */

    public JSONObject multifileUploadService(HttpServletRequest request) throws Exception {
    //  多文件上传获取
    //  List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("fileName");
        if (null == file || file.isEmpty()) {
            return OwinfoResultUtil.failure(null, "文件未上传,请选择文件");
        }
        //文件路径
        String path = fileHelper.getFileStorage();
        //for(MultipartFile file:files){
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(fileName + "-->" + suffix + "-->" + size);
        fileName = fileName.replace(".", "-" + System.currentTimeMillis() + ".");
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        if (dest.exists()) {
            return OwinfoResultUtil.failure(null, "文件已存在");
        }
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            throw e;
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("fileName", fileName);
        resMap.put("fileUrl", path + "/" + fileName);
        resMap.put("fileType", suffix);
        //}
        return OwinfoResultUtil.success(resMap, "上传成功");
    }
}
ˆ Back To Top