search
HomeJavajavaTutorialHow to use Java server to process image uploads

1. Brief description

First: Implementation of browser uploading images;

Second: Implementation of WeChat applet uploading images;

Second. Implementation of image upload function

1. Implementation of processing H5 single file upload:

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. Code implementation of uploading image files on WeChat or mobile 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;
    }
 
}

The above is the detailed content of How to use Java server to process image uploads. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

How does Java's platform independence facilitate code reuse?How does Java's platform independence facilitate code reuse?Apr 24, 2025 am 12:05 AM

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

How do you troubleshoot platform-specific issues in a Java application?How do you troubleshoot platform-specific issues in a Java application?Apr 24, 2025 am 12:04 AM

To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software