搜索
首页Javajava教程怎么使用Java服务器处理图片上传

一、简述

第一:浏览器上传图片实现;

第二:微信小程序上传图片实现;

二、图片上传功能实现

1.处理H5的单文件上传实现:

package cn.ncist.tms.attachment.controller;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
/**
 * 附件上传类
 * 
 * @author Fxh
 *
 */
@RequestMapping(value = "/fileUpload")
@Controller
public class AttachmentUpload {
    
    /**
     * 上传文件功能,以Post请求发送请求,
     * 
     * @param request:请求对象
     * @param reponse:响应对象
     * @param file:上传的文件对象
     * @return JSON串 : {"code":"S","msg":"服务调用成功"}
     * @throws IOException 
     */
    @RequestMapping(value = "/doFileUpload",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> doFileUpload(HttpServletRequest request,
            HttpServletResponse reponse,
            @RequestParam("file") MultipartFile srcFile) throws IOException{
        
        /*
         * 注意:传入参数时,文件的注解@ReuqestParam("variable") -->variable指:前端的h6的控件的name值.
         * 
         * 文件处理功能: 1.将获取的字节数组转化为文件对象,并保存在本地目录中;
         * 
         * 文件处理思路: 1.将获取的(source)file对象,通过函数获取字节数组;
         *                 2.实例化文件对象和文件输出流;
         *                 3.将字节数组写入文件即可.
         * 
         * 功能难度: 简单.
         */
        
        //1.变量声明
        Map<String,Object> result = null;// 返回结果变量
        FileOutputStream fos = null;     //写入文件的变量
        File destFile = null;    //写入的目的地文件(distination)
        
        try {
            result = new HashMap<String,Object>();
            
            //2.参数验证
            if(srcFile == null){
                throw new RuntimeException("上传文件不存在");
            }
            if(srcFile.getBytes().length == 0){
                throw new RuntimeException("上传文件内容为空");
            }
            
            //3.操作文件对象,写入本地目录的文件中
            
            //3.1 截取文件后缀
            String ext = srcFile.getOriginalFilename().substring(srcFile.getContentType().lastIndexOf( ".")+1);
            //3.2 实例化目标文件,根据当前的操作系统,指定目录文件,
            destFile = new File("D:"+File.separator+"descFolder"+File.separator+"descFile."+ext);
            //3.3 实例化流
            fos = new FileOutputStream(destFile);
            //3.4 获取写入的字节数组,并写入文件    
            byte[] srcBytes = srcFile.getBytes();
            fos.write(srcBytes);
            fos.flush();
            //4.对输入、输出流进行统一管理
            //已在文件finally代码块处理
            
            result.put( "code", "S");
            result.put( "msg", "服务调用成功");
            result.put( "path", destFile.getAbsolutePath());
            return result;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            result = new HashMap<String,Object>();
            result.put( "code", "F");
            result.put( "msg", "服务调用失败");
            result.put( "path", null);
            return result;
        } finally{
            //关闭系统资源,避免占用资源.
            if(fos != null){
                fos.close();
            }
        }
    }
}

2.微信或手机APP上传图片文件的代码实现:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
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 com.hlinkcloud.ubp.core.constant.RedisKeyConstant;
import com.hlinkcloud.ubp.core.service.RedisService;
import com.hlinkcloud.ubp.core.util.BaseStringUtil;
import com.hlinkcloud.ubp.facade.bean.common.FastDFSFile;
import com.hlinkcloud.ubp.facade.bean.common.FileManagerConfig;
import com.hlinkcloud.ubp.facade.service.common.FileInfoService;
import com.hlinkcloud.ubp.facade.service.permission.UserService;
import com.hlinkcloud.ubp.facade.util.DictionaryCommUtil;
 
import fr.opensagres.xdocreport.core.io.internal.ByteArrayOutputStream;
 
/**
 * 微信上传图片业务
 * 
 * @author FengQi
 *
 */
@Controller
@RequestMapping("/wx_upload")
public class WxUploadImgBusiness {
 
    @Resource
    private UserService userService;
 
    @Resource
    private RedisService redisService;
 
    @Resource(name = "commonUtil")
    private DictionaryCommUtil commUtil;
 
    @Resource
    private FileInfoService fileService; /* 文件服务 */
    
    @RequestMapping("/getUploadFilePath")
    @ResponseBody
    public Map<String, Object> doWxUploadFile(HttpServletRequest request, HttpServletResponse response) {
 
        HashMap<String, Object> map = new HashMap<String, Object>();
        
        try {
            
            /*
             * // 注释:该部分是使用在没有使用sprinvMVC的架构下的图片上传. // 1.磁盘文件条目工厂
             * DiskFileItemFactory factory = new DiskFileItemFactory();
             * 
             * //2.1 高速的文件上传处理类 ServletFileUpload sfu = new
             * ServletFileUpload(factory);
             * 
             * List<FileItem> list = sfu.parseRequest(request); FileItem picture
             * = null; if(list != null && list.size() > 0){ for(FileItem item :
             * list){ if(!item.isFormField()){ picture = item; } } }
             */
 
            // 1.将请求转化为操作流的请求对象.
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile picture = req.getFile("file");
            
            if(picture != null && picture.getBytes().length != 0){
                // 2.将图片上传到服务器
                byte[] bytes = picture.getBytes();
                String ext = picture.getOriginalFilename().substring(
                        picture.getOriginalFilename().lastIndexOf(".") + 1
                        );
                // (备注:下列代码为内部业务代码,可根据公司自身的需求,进行更改)
                
                
                map.put("code", "S");
                map.put( "msg", "服务调用成功");
                map.put("statusCode", 200);
                map.put("data", filePath);
            }else{
                throw new RuntimeException("上传图片异常或空图片!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            map.put("code", "F");
            map.put("msg", "服务调用失败");
            map.put("statusCode", 500);
            map.put("data", null);
        }
        return map;
    }
    
    /**
     * 当不知道手机、微信传入前端的参数是什么时,
     * 
     * 可调用该接口进行判断.
     * 
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/doUploadFileOfCI" , method = RequestMethod.POST )
    public @ResponseBody Map<String,Object> doUploadFile(
            HttpServletRequest request,//请求对象
            HttpServletResponse response) throws IOException{//响应对象
        
        System.out.println("doTestMultipartFile:");
        
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        //此时说明请求对象是MultipartHttpServletRequest对象
        MultipartFile picture = req.getFile("UploadedImage");
        
        //遍历请求得到所有的数据.
        if(req != null){
            
            //获取所有属性名
            Enumeration enume= req.getAttributeNames();
            while(enume.hasMoreElements()){
                System.out.println("enume:"+enume.nextElement());
            }
            
            //获取所有文件名
            Iterator<String> fileNames = req.getFileNames();
            while(fileNames.hasNext()){
                System.out.println("fileNames:"+fileNames.next());
            }
            
            //获取操作文件的map
            Map<String,MultipartFile> fileMap =  req.getFileMap();
            if(fileMap != null && fileMap.size() > 0){
                Set<String> set = fileMap.keySet();
                for(String key:set){
                    System.out.println("String:"+key);
                }
            }
            
            //获取请求流
            InputStream is = req.getInputStream();
            System.out.println("InputStream:"+is);
            int length = -1;
            while( (length = is.read()) != -1 ){
                System.err.println("data:"+length);
            }
            
            //获取所有请求参数
            Enumeration enumee = req.getParameterNames();
            while(enumee.hasMoreElements()){
                System.out.println("enumee:"+enumee.nextElement());
            }
        }
        
        System.out.println(picture);
        
        
        return null;
    }
 
}

以上是怎么使用Java服务器处理图片上传的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
是否有任何威胁或增强Java平台独立性的新兴技术?是否有任何威胁或增强Java平台独立性的新兴技术?Apr 24, 2025 am 12:11 AM

新兴技术对Java的平台独立性既有威胁也有增强。1)云计算和容器化技术如Docker增强了Java的平台独立性,但需要优化以适应不同云环境。2)WebAssembly通过GraalVM编译Java代码,扩展了其平台独立性,但需与其他语言竞争性能。

JVM的实现是什么,它们都提供了相同的平台独立性?JVM的实现是什么,它们都提供了相同的平台独立性?Apr 24, 2025 am 12:10 AM

不同JVM实现都能提供平台独立性,但表现略有不同。1.OracleHotSpot和OpenJDKJVM在平台独立性上表现相似,但OpenJDK可能需额外配置。2.IBMJ9JVM在特定操作系统上表现优化。3.GraalVM支持多语言,需额外配置。4.AzulZingJVM需特定平台调整。

平台独立性如何降低发展成本和时间?平台独立性如何降低发展成本和时间?Apr 24, 2025 am 12:08 AM

平台独立性通过在多种操作系统上运行同一套代码,降低开发成本和缩短开发时间。具体表现为:1.减少开发时间,只需维护一套代码;2.降低维护成本,统一测试流程;3.快速迭代和团队协作,简化部署过程。

Java的平台独立性如何促进代码重用?Java的平台独立性如何促进代码重用?Apr 24, 2025 am 12:05 AM

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

您如何在Java应用程序中对平台特定问题进行故障排除?您如何在Java应用程序中对平台特定问题进行故障排除?Apr 24, 2025 am 12:04 AM

要解决Java应用程序中的平台特定问题,可以采取以下步骤:1.使用Java的System类查看系统属性以了解运行环境。2.利用File类或java.nio.file包处理文件路径。3.根据操作系统条件加载本地库。4.使用VisualVM或JProfiler优化跨平台性能。5.通过Docker容器化确保测试环境与生产环境一致。6.利用GitHubActions在多个平台上进行自动化测试。这些方法有助于有效地解决Java应用程序中的平台特定问题。

JVM中的类加载程序子系统如何促进平台独立性?JVM中的类加载程序子系统如何促进平台独立性?Apr 23, 2025 am 12:14 AM

类加载器通过统一的类文件格式、动态加载、双亲委派模型和平台无关的字节码,确保Java程序在不同平台上的一致性和兼容性,实现平台独立性。

Java编译器会产生特定于平台的代码吗?解释。Java编译器会产生特定于平台的代码吗?解释。Apr 23, 2025 am 12:09 AM

Java编译器生成的代码是平台无关的,但最终执行的代码是平台特定的。1.Java源代码编译成平台无关的字节码。2.JVM将字节码转换为特定平台的机器码,确保跨平台运行但性能可能不同。

JVM如何处理不同操作系统的多线程?JVM如何处理不同操作系统的多线程?Apr 23, 2025 am 12:07 AM

多线程在现代编程中重要,因为它能提高程序的响应性和资源利用率,并处理复杂的并发任务。JVM通过线程映射、调度机制和同步锁机制,在不同操作系统上确保多线程的一致性和高效性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。