图片上传 / 图片与简单字段的混合上传

本文介绍了一个表单实现,包含图片上传域和简单文本域,并详细阐述了如何利用Apache Commons FileUpload和JSTL等组件进行图片上传和文本收集。包括配置文件路径、上传文件类型限制、文件大小限制、文件名生成、错误处理及前后端交互流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 描述:一个form表单中同时包含图片上传域和简单的text域
  • 依赖:
    • commons-fileupload-1.2.2.jar
    • commons-io-2.4.jar
    • jstl.jar
    • standard.jar
    • servlet-api.jar
  • 代码:
    • FileUpload.java
      • package fileupload;
        
        import java.io.File;
        import java.io.IOException;
        import java.util.List;
        import java.util.UUID;
        
        import javax.servlet.ServletException;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        
        import org.apache.commons.fileupload.FileItem;
        import org.apache.commons.fileupload.FileUploadException;
        import org.apache.commons.fileupload.disk.DiskFileItemFactory;
        import org.apache.commons.fileupload.servlet.ServletFileUpload;
        
        import util.FileUtil;
        
        @WebServlet(urlPatterns = { "/UploadFile" })
        public class FileUpload extends HttpServlet {
            
            private static final long serialVersionUID = 1L;
        
            @SuppressWarnings("unchecked")
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                
                //上传图片的最大大小
                int maxSize = 3;
                //允许的图片类型
                String[] imgTypes = {".jpg",".gif",".bmp",".png",".jpeg",".ico"};
                //上传文件的目录
                String uploadFullPath = FileUtil.UPLOAD_DIR;
                //上传文件的临时目录
                String uploadTempFullPath = FileUtil.UPLOAD_DIR + File.separator + "tmp";
                
                if(!new File(uploadFullPath).isDirectory()){
                    new File(uploadFullPath).mkdirs(); 
                }   
                
                if(!new File(uploadTempFullPath).isDirectory()){   
                    new File(uploadTempFullPath).mkdirs();
                }
                
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //设置最大缓存
                factory.setSizeThreshold(5*1024);
                factory.setRepository(new File(uploadTempFullPath));
            
                ServletFileUpload upload = new ServletFileUpload(factory);
                //设置文件大小上限
                upload.setSizeMax(maxSize*1024*1024);
                
                String filePath = null;
                String simpleField = null;
                
                List<FileItem> fileItems = null;
                try {
                    fileItems = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
                
                for (FileItem fileItem : fileItems) {
                    
                    if (!fileItem.isFormField()) {
                        String fileName = fileItem.getName().toLowerCase();
                        if (fileName.endsWith(imgTypes[0])
                                || fileName.endsWith(imgTypes[1])
                                || fileName.endsWith(imgTypes[2])
                                || fileName.endsWith(imgTypes[3])
                                || fileName.endsWith(imgTypes[4])
                                || fileName.endsWith(imgTypes[5])) {
                            
                            String uuid = UUID.randomUUID().toString();
                            String generateFullFileName = uuid + fileName.substring(fileName.lastIndexOf("."));
                            filePath = uploadFullPath + File.separator + generateFullFileName;
                            
                            System.out.println("filePath: " + filePath);
                            
                            try {
                                fileItem.write(new File(filePath));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            
                            request.setAttribute("fullFilePath", filePath);
                            request.setAttribute("imgUrl", "/img/" + generateFullFileName);
                            
                        } else {
                            request.setAttribute("failMessage", "上传失败,请确定你选择的文件为图片!");
                        }
                    }
                    
                    if (fileItem.isFormField()) {
                        String fieldName = fileItem.getFieldName();
                        if ("simpleField".equals(fieldName)) {
                            String value = new String(fileItem.getString("utf-8"));
                            if (value != null && value.length() > 0) {
                                simpleField = value;
                                request.setAttribute("simpleField", simpleField);
                            }
                        }
                    }
                    
                }
                
                request.getRequestDispatcher("/fileupload/fileUpload.jsp").forward(request, response);
            }
        
        }
        
    • FileUtil.java
      • package util;
        
        import java.io.File;
        import java.io.FileInputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.Reader;
        import java.nio.ByteBuffer;
        import java.util.Properties;
        
        public class FileUtil {
        
            public static String UPLOAD_DIR;
            
            static {
                
                Properties properties = new Properties();
                
                InputStream is = FileUtil.class.getResourceAsStream("/project.properties");
                try {
                    properties.load(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new InternalError(e.getMessage());
                }
                
                String osType = System.getProperty("os.name").toLowerCase();
                
                if (osType.indexOf("win") >= 0) {
                    UPLOAD_DIR = properties.getProperty("WIN_UPLOAD_DIR");
                } else if (osType.indexOf("mac") >= 0) {
                    UPLOAD_DIR = properties.getProperty("MAC_UPLOAD_DIR");
                } else if (osType.indexOf("nix") >= 0 || osType.indexOf("nux") >= 0) {
                    UPLOAD_DIR = properties.getProperty("NIX_UPLOAD_DIR");
                } else if (osType.indexOf("sunos") >= 0) {
                    UPLOAD_DIR = properties.getProperty("SOL_UPLOAD_DIR");
                } else {
                    throw new InternalError("Your system is not supported!");
                }
                
            }
            
            public static byte[] readIntoByteArray(String fileName) throws IOException {
                FileInputStream fis = null;
                
                File file = new File(fileName);
                
                if (Integer.MAX_VALUE <= file.length()) {
                    throw new RuntimeException("File is too big, and length = " + file.length());
                }
                
                try {
                    fis = new FileInputStream(file);
                    ByteBuffer bb = ByteBuffer.allocate((int)file.length());
                    
                    int bytesRead = fis.getChannel().read(bb);
                    
                    if (bytesRead != file.length()) {
                        throw new IOException("Error occurred while reading file, bytes = " + bytesRead);
                    }
                    
                    return bb.array();
                } catch (IOException e) {
                    throw new IOException(e.getLocalizedMessage());
                } finally {
                    if (fis != null) {
                        fis.close();
                    }
                }
                
            }
            
            /*
             * http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file
             */
            public static String readIntoString(InputStream is, String encoding) throws IOException {
                final char[] buffer = new char[0x2000];
                
                StringBuilder out = new StringBuilder();
                
                Reader in = new InputStreamReader(is, encoding != null ? encoding : "UTF-8");
                
                int read;
                
                do {
                    read = in.read(buffer, 0, buffer.length);
                    
                    if (read > 0) {
                        out.append(buffer, 0, read);
                    }
                    
                } while (read >= 0);
                
                return out.toString();
            }
            
            public static void deleteDir(String filePath) {
                File file = new File(filePath);
                if (file.exists() && file.isDirectory()) {
                    if (file.listFiles().length == 0) {
                        file.delete();
                    } else {
                        File[] deleteFile = file.listFiles();
                        int i = file.listFiles().length;
                        for (int j = 0; j < i; j ++) {
                            if (deleteFile[j].isDirectory()) {
                                deleteDir(deleteFile[j].getAbsolutePath());
                            }
                            deleteFile[j].delete();
                        }
                        file.delete();
                    }
                }
            }
            
        }
        
    • project.properties
      • WIN_UPLOAD_DIR=C:\\upload\\public
        #MAC_UPLOAD_DIR=
        #NIX_UPLOAD_DIR=
        #SOL_UPLOAD_DIR=
    • fileUpload.jsp
      • <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <html>
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                <link href="../css/global.css" rel="stylesheet" type="text/css"/>
                <title>File Upload</title>
            </head>
            
            <body>
                <div class="headContainer">
                    <div class="header"></div>
                </div>
                
                <div class="mainContainer">
                    <div>
                        <form id="fileUpload" name="fileUpload" method="post" enctype="multipart/form-data" action="/FileUpload/UploadFile">
                            <label>Simple Field : </label><input id="simpleField" name="simpleField" type="text" />
                            <br />
                            <label>Upload Files : </label><input type="file" name="fileUpload" />
                            <br />
                            <input type="submit" value="Submit" />
                            <input type="reset" value="Reset" />
                        </form>
                    </div>
                    <div id="echo">
                        <img src="${imgUrl}" />
                        <br />
                        <span id="fullFilePath">${fullFilePath}</span>
                        <br />
                        <span id="simpleField">${simpleField}</span>
                    </div>
                </div>
                
                <div class="footContainer">
                    <div class="footer"></div>
                </div>
            </body>
        </html>
  • PS:
    • Windows下可为上传的图片目录在Application Server专门设置一个虚拟目录,这样client就可以访问图片了
    • 设置虚拟目录方式同设置虚拟开发目录,如:
      <context path="/img" docbase="C:\upload\public" reloadable="true"></context>
    • 设置了虚拟目录,只对该目录下的文件有权限,对该目录下的目录依然是无权限访问的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值