于世海
于世海
  • 发布:2016-02-17 11:47
  • 更新:2019-01-20 17:21
  • 阅读:12349

使用Uploader上传文件,Java做后端的处理方法

分类:HTML5+

由于刚刚接触HTML5+开发APP,对于后端处理不太了解,昨天还发帖询问呢,但是没有人回答,经过不懈的努力,终于搞定了,现将后端处理的代码分享上来!
此程序需要的jar包如下:
commons-fileupload-1.2.1.jar
commons-io-1.4.jar
需将两个jar包放到工程的lib文件夹下,上传页面的代码我用的是HelloH5+项目的uploader.html,这个应该很好找,后端的上传处理我用的是Servlet,具体的配置方法就不讲了,直接来代码:

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.Calendar;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Random;  
import java.util.UUID;  

import javax.servlet.ServletException;  
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.FileUploadBase;  
import org.apache.commons.fileupload.ProgressListener;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
/**  
 * Apache组件上传  
 *   
 * @author 于世海  
 * @date 2016-02-17  
 */  
public class UploadHandleServlet extends HttpServlet {  

    private static final long serialVersionUID = 5827821285414610443L;  

    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        this.doPost(request, response);  
    }  

    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        // 上传文件目录  
        String uploadDir = this.getServletContext().getRealPath("/upload");  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        // 设置内存区块大小4KB  
        factory.setSizeThreshold(4 * 1024);  
        // 设置暂存容器,当上传文件大于设置的内存块大小时,用暂存容器做中转  
        factory.setRepository(new File(this.getServletContext().getRealPath(  
                "/temp")));  
        ServletFileUpload fileUpload = new ServletFileUpload(factory);  
        fileUpload.setSizeMax(1024 * 1024 * 100);  
        //fileUpload.setFileSizeMax(1024 * 1024 * 10);  
        List<FileItem> fileItemList = null;  

        try {  
            fileItemList = fileUpload.parseRequest(request);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        Iterator<FileItem> fileItemIterator = fileItemList.iterator();  
        FileItem fileItem = null;  
        while (fileItemIterator.hasNext()) {  
            fileItem = fileItemIterator.next();  
            // 普通文件框上传  
            if (fileItem.isFormField()) {  
                String filedName = fileItem.getFieldName();  
                String filedValue = fileItem.getString("GBK");// 编码格式  
                System.out.println(filedName);// 文件框名称  
                System.out.println(filedValue);// 文件的值  
            } else {  
                String filedName = fileItem.getFieldName();// 文件上传框的名称  
                // 获取文件上传的文件名  
                String OriginalFileName = takeOutFileName(fileItem.getName());  
                System.out.println("原始文件名:"+OriginalFileName);  
                if (!"".equals(OriginalFileName)) {  
                    // 根据上传的文件名重新命名  
                    String newFileName = getNewFileName(OriginalFileName);  
                    System.out.println("重新名:"+newFileName);  
                    File writeToFile = new File(uploadDir + File.separator  
                            + newFileName);  
                    try {  
                        fileItem.write(writeToFile);  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
    }  

    private String takeOutFileName(String filePath) {  
        String fileName = filePath;  
        if (null != filePath && !"".equals(filePath)) {  
            int port = filePath.lastIndexOf("\\");  
            if(port != -1){  
                fileName = filePath.substring(port+1);  
            }  
        }  
        return fileName;  
    }  

    private String getNewFileName(String originalFileName) {  
        StringBuffer newFileName = new StringBuffer();  
        if (null != originalFileName && !"".equals(originalFileName)) {  
            int port = originalFileName.lastIndexOf(".");  
            String type = "";  
            String fileName = "";  
            if (port != -1) {  
                type = originalFileName.substring(port + 1);  
                fileName = originalFileName.substring(0, port);  
            } else {  
                fileName = originalFileName;  
            }  
            StringBuffer suffix = new StringBuffer("_");  
            suffix.append(Calendar.getInstance().getTimeInMillis());  
            suffix.append("_");  
            suffix.append(new Random().nextInt(100));  
            newFileName.append(fileName);  
            newFileName.append(suffix);  
            newFileName.append(".");  
            newFileName.append(type);  
        }  
        return newFileName.toString();  
    }  

}

其他的处理代码直接修改就可以了!

8 关注 分享
z***@sina.com c***@163.com l***@126.com 1***@qq.com Trust 1***@139.com 6465262 7***@qq.com

要回复文章请先登录注册

1***@139.com

1***@139.com

在目录中新建upload和temp文件夹后,将代码直接运行无报错,非常棒,留名备用
2019-01-20 17:21
7***@qq.com

7***@qq.com

mark
2018-01-16 16:32
s***@foxmail.com

s***@foxmail.com

addData后台取不出来诶
2017-12-06 22:49
于世海

于世海 (作者)

回复 1***@qq.com :
参考一下HelloH5+项目的uploader.html,直接去官方下载一个研究一下即可
2017-03-14 09:05
1***@qq.com

1***@qq.com

那这个前台如何调用呢,plus.uploader.createUpload(server,这里这个sever怎么写呢
2017-03-10 15:37
于世海

于世海 (作者)

回复 g***@163.com :
自己建一个upload文件夹
2017-01-13 16:19
l***@126.com

l***@126.com

mark
2016-12-21 16:52
g***@163.com

g***@163.com

执行报错误java.lang.NullPointerException: null
发现是如下这句:
String uploadDir = this.getServletContext().getRealPath("/upload");
2016-12-10 19:01
dahu

dahu

thanks!!!!!
2016-08-15 14:12
小小码农

小小码农

mark
2016-08-01 17:37