java上传文件的几种方式_javaweb文件上传

java上传文件的几种方式_javaweb文件上传1、ServletFileUpload  表单提交中当提交数据类型是multipare/form-data类型的时候,如果我们用servlet去做处理的话,该http请求就会被servlet容器,包装成httpservletRequest对象  ,在由相应的servlet进行处理。packagecom.jws.app.operater.service.impl;…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

1、ServletFileUpload

  表单提交中当提交数据类型是multipare/form-data类型的时候,如果我们用servlet去做处理的话,该http请求就会被servlet容器,包装成httpservletRequest对象

  ,在由相应的servlet进行处理。

    

java上传文件的几种方式_javaweb文件上传
java上传文件的几种方式_javaweb文件上传

package com.jws.app.operater.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import net.sf.json.JSONObject;

import com.jws.app.operater.data.UserInfoMapper;
import com.jws.app.operater.model.UserInfo;
import com.jws.app.operater.service.PersionPhoteAuthServer;
import com.jws.common.constant.Constants;
import com.jws.common.constant.ConstantsCode;
import com.jws.common.util.JiveGlobe;
import com.jws.common.util.ResultPackaging;

@Service("persionPhoteAuthServerImpl")
public class PersionPhoteAuthServerImpl implements PersionPhoteAuthServer {
    @Resource
    private UserInfoMapper userInfoMapper;
    private final Logger logger = Logger.getLogger(this.getClass());

    @Override
    public JSONObject uploadPhoto(HttpServletRequest reques) {
        JSONObject returnObject = new JSONObject();
        String path =  Constants.imageUrl;
        File repositoryFile = new File(path);
        if (!repositoryFile.exists()) {repositoryFile.mkdirs();}
        FileItemFactory factory = new DiskFileItemFactory(1024 * 32,repositoryFile);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        upload.setSizeMax(1024 * 1024 * 500);
        List<?> fileItr = null;
        try {
             fileItr = upload.parseRequest(reques);
                // 讲非文件值放在map中
                HashMap<String, String> map = new HashMap<>();
                Iterator<?> iter = fileItr.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        map.put(item.getFieldName(), item.getString());
                    }
                }
                // 验证参数
                if (map == null || !map.containsKey("openid")) {
                    returnObject =ResultPackaging.dealJsonObject(ConstantsCode.RESULT_CODE_FAIL, ConstantsCode.CODE_LACK_PARAMETER, null);
                    return returnObject;            
                }
                String openid  = map.get("openid");
                //处理文件
                boolean isTrue = true;
                String filename = "";
                Iterator<?> iter1 = fileItr.iterator();
                while (iter1.hasNext()) {
                    FileItem f = (FileItem) iter1.next();
                    if (!f.isFormField()) {
                //详情 name=abc.png,  size=376507 bytes,     isFormField=false, FieldName=picture1
                        filename = f.getName() == null ? "" : f.getName();
                        filename = JiveGlobe.getFromRom()+".jpg";
                        File saveFile = new File(path, filename);
                        if (saveFile.exists()) {
                            isTrue = false;break;}
                            f.write(saveFile);
                        } 
            }
            if(JiveGlobe.isEmpty(filename)){
                returnObject =ResultPackaging.dealJsonObject(ConstantsCode.RESULT_CODE_FAIL, ConstantsCode.CODE_LACK_PARAMETER, null);
                return returnObject;            
            }
            returnObject =ResultPackaging.dealJsonObject(ConstantsCode.RESULT_CODE_SUCCESS, ConstantsCode.RESULT_CODE_SUCCESS, null);
            //保存文件信息
            UserInfo rd = new UserInfo();
            rd.setSpareField1("1");
            rd.setSpareField3(filename);
            rd.setOpenId(openid);
            userInfoMapper.updateByPrimaryKey(rd);
        } catch (Exception e) {
            System.out.println(e);
            logger.error("###认证失败"+e);
        }
        return returnObject;
    }
    
    
}

View Code

 

2、MultipartFile

   

java上传文件的几种方式_javaweb文件上传
java上传文件的几种方式_javaweb文件上传

@RequestMapping("/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为:" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为:" + suffixName);
        // 文件上传后的路径
        String filePath = "D://";
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

View Code

java上传文件的几种方式_javaweb文件上传
java上传文件的几种方式_javaweb文件上传

/**
     * 多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
    public @ResponseBody String handleFileUpload1(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filePath = "D://";
        MultipartFile file = null;

        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            // 获取文件名
            String fileName = file.getOriginalFilename();
            System.out.println("上传的文件名为:" + fileName);

            if (!file.isEmpty()) {
                File dest = new File(filePath + fileName);
                // 检测是否存在目录
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                try {
                    file.transferTo(dest);
                } catch (Exception e) {
                    return "上传失败 " + i + " => " + e.getMessage();
                }
            } else {
                return "上传失败 " + i + " 文件为空.";
            }
        }
        return "上传成功";
    }

View Code

 

3、CommonsMultipartResolver

  

 *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(“/uploadFile”)
    public Map<String, Object> uploadFile(HttpServletRequest request) {

        Map<String, Object> map = new HashMap<String, Object>();
        // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 检查form中是否有enctype=”multipart/form-data”
        if (multipartResolver.isMultipart(request)) {

            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {

                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                try {

                    if (file != null && StringUtils.isNotBlank(file.getOriginalFilename().trim())) {

                        Map<String, String> metas = new HashMap<String, String>();
                        // 取得文件后缀
                        String filename = file.getOriginalFilename();
                        String newFileName = System.currentTimeMillis() + (int) (Math.random() * 100)
                                + filename.substring(filename.lastIndexOf(“.”));
                        metas.put(StorageConstants.META_KEY_FILENAME, newFileName);
                        String imgUrl = storageService.store(file.getBytes(), metas);
                        map.put(“imgUrl”, imgUrl);
                        map.put(“retCode”, “success”);
                        // map.put(“imgUrl”,
                        // “https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=611483611,2895064642&fm=117&gp=0.jpg”);
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        } else {

            map.put(“retCode”, “error”);
        }
        return map;

 

转载于:https://www.cnblogs.com/kimobolo/p/7109999.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/197140.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 运维面试题(面前准备)

    运维面试题(面前准备)前段时间一直在面试,也没怎么写博客,现在找到实习工作了,也有时间去写了。在这里分享一下我面试之前做的一些准备。(以下内容是我从网上查找整理得到的…红色标注为面试提及的,但不一定是我整理的内容)TCP/IP简述TCP三次握手的过程?答:在TCP/IP协议中,TCP协议提供可靠的连接服务,采用三次握手建立一个连接。第一次握手:建立连接时,客户端发送syn包(syn=j)到服务器…

    2022年6月14日
    40
  • SpringCloud系列之客户端负载均衡Netflix Ribbon

    SpringCloud系列之客户端负载均衡Netflix Ribbon

    2020年11月19日
    182
  • HDP kt_renewer ERROR Couldn‘t renew kerberos ticket in order to work around Kerberos 1.8.1 issu

    HDP kt_renewer ERROR Couldn‘t renew kerberos ticket in order to work around Kerberos 1.8.1 issu完整报错:kt_renewerERRORCouldn’trenewkerberosticketinordertoworkaroundKerberos1.8.1issue.Pleasecheckthattheticketfor’hue/client-v01.16899.com@16899.COM’isstillrenewable:

    2025年7月14日
    4
  • mysql listagg函数_Oracle函数之LISTAGG「建议收藏」

    mysql listagg函数_Oracle函数之LISTAGG「建议收藏」最近在学习的过程中,发现一个挺有意思的Oracle函数,它可实现对列值的拼接。下面我们来看看其具体用法。最近在学习的过程中,发现一个挺有意思的Oracle函数,它可实现对列值的拼接。下面我们来看看其具体用法。用法:对其作用,官方文档的解释如下:Foraspecifiedmeasure,LISTAGGordersdatawithineachgroupspecifiedinth…

    2025年9月26日
    6
  • Docker(五)[通俗易懂]

    Docker(五)[通俗易懂]DockerDocker网络–link自定义网络网络连通Docker网络Docker是如何进行网络通讯的?查看本机的网卡和ip地址docker0类似与路由器ip地址一样(x.x.x.1)Dockerdocker run -d -P –name=tomcat03 tomcat:8.0查看容器ip地址docker exec -it a72d4ae634da ip addr1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noque

    2022年8月11日
    12
  • 加壳工具简介「建议收藏」

    加壳工具简介「建议收藏」
    1.程序编写语言:
    常见的程序制作语言有:
    BorlandDelphi6.0-7.0
    MicrosoftVisualC++6.0
    MicrosoftVisualBasic5.0/6.0
    还有汇编、易语言等。很多软件都通过加壳保护来提高软件的激活成功教程难度,下面我们简单的介绍一下加壳工具。
    2.软件加壳工具介绍:
    II压缩壳介绍:
    常见压缩壳有:ASPack、UPX、PeCompact、N

    2022年6月27日
    114

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号