怎样将压缩文件上传到服务器上

前言: 由于项目api是一台服务器,upload也是一台服务器,所以整体思路就是

1,先将zip上传到upload服务器

2,在upload服务器上解压zip。

3,在upload服务器上处理解压的文件(基本上都是json string)

4,通过接口调用将json string传入到接口中,进行数据库的操作

一、html

<input id="discoverImg" type="file" name="" class="layui-input">
<input type=‘button‘ class="layui-btn layui-btn-primary" onclick="getImg()" value=‘生成图片‘></input>

二、JS

function getImg(){

var zipUpdate = $("#zipId")[0].files[0];var formData = new FormData();
formData.append("zipFile",zipUpdate);
uploadZip(formData,callback);

}

function uploadZip(formData, callback){

$.ajax({    url : ‘/uploadZip‘,    method : ‘POST‘,    async: false,    processData: false,    contentType:false,    data : formData,    success : function(result) {        callback(result)    }})

}

function callback(result){    if(result.resultCode==1){        var emojiName = $(".emojiName").val();        // var emojiPath = $(".emojiPath").val();        var emojiProfile = $(".emojiProfile").val();        var emojiEveryName = $(".emojiEveryName").val();        var emojiPath = JSON.stringify(result.data);//将data转化成json String        Common.invoke({            path : ‘/add‘,            data : {                ‘zipName‘:emojiName,                ‘zipPath‘:emojiPath,//json String                ‘zipProfile‘: emojiProfile,                ‘nameStr‘ :emojiEveryName            },            successMsg : "",            errorMsg : "",            successCb : function(result) {

                }            },            errorCb : function(result) {            }        });    }}

三、Java、

//一下代码主要是组装访问upload的request和解析结果

public static Map getUploadZipPath(String domain,MultipartFile multipartFile){      String newUrl=null;      Map mapImags = new HashMap();      try {         // 换行符         final String newLine = "\r\n";         final String boundaryPrefix = "--";         // 定义数据分隔线         String BOUNDARY = "========7d4a6d158c9";         // 服务器的域名         URL url = new URL(domain+"/upload/UploadZipServlet");         HttpURLConnection conn = (HttpURLConnection) url.openConnection();         // 设置为POST情         conn.setRequestMethod("POST");         // 发送POST请求必须设置如下两行         conn.setDoOutput(true);         conn.setDoInput(true);         conn.setUseCaches(false);         // 设置请求头参数         conn.setRequestProperty("connection", "Keep-Alive");         conn.setRequestProperty("Charsert", "UTF-8");         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);         OutputStream out = new DataOutputStream(conn.getOutputStream());         // 上传文件         String fileRealName = multipartFile.getOriginalFilename();//获得原始文件名;         StringBuilder sb = new StringBuilder();         sb.append(boundaryPrefix);         sb.append(BOUNDARY);         sb.append(newLine);         // 文件参数,photo参数名可以随意修改         sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileRealName + "\"" + newLine);         sb.append("Content-Type:application/octet-stream");         // 参数头设置完以后需要两个换行,然后才是参数内容         sb.append(newLine);         sb.append(newLine);         // 将参数头的数据写入到输出流中         out.write(sb.toString().getBytes());         // 数据输入流,用于读取文件数据         DataInputStream in = new DataInputStream(multipartFile.getInputStream());         byte[] bufferOut = new byte[1024];         int bytes = 0;         // 每次读1KB数据,并且将文件数据写入到输出流中         while ((bytes = in.read(bufferOut)) != -1) {            out.write(bufferOut, 0, bytes);         }         // 最后添加换行         out.write(newLine.getBytes());         in.close();         // 定义最后数据分隔线,即--加上BOUNDARY再加上--。         byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();         // 写上结尾标识         out.write(end_data);         out.flush();         out.close();//          定义BufferedReader输入流来读取URL的响应         BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));         JSONObject resultObj = JSON.parseObject(reader.readLine());         JSONObject resultData= resultObj.getJSONObject("data");         if(null == resultData)            throw new ServiceException("源文件不存在");         JSONArray imagesData = resultData.getJSONArray("images");         JSONArray imagesDataOthers = resultData.getJSONArray("zip");         List zipImags = Lists.newArrayList();         List zip = Lists.newArrayList();         if (imagesData.size() > 0){            for(int i = 0; i< imagesData.size(); i++){               JSONObject imageData = imagesData.getJSONObject(i);               String newUrlO = imageData.getString("oUrl");               String newUrlT = imageData.getString("tUrl");               System.out.println(" upload new Url =====>"+newUrlO);               System.out.println(" upload new Url =====>"+newUrlT);               newUrl = newUrlO + "," + newUrlT;               zipImags.add(newUrl);            }            mapImags.put("imags",zipImags);         }         if(imagesDataOthers.size()>0){            JSONObject imageDataOthers = imagesDataOthers.getJSONObject(0);            String newUrlOthers = imageDataOthers.getString("oUrl");            zip.add(newUrlOthers);            mapImags.put("zip",zip);         }

      } catch (Exception e) {         System.out.println("发送POST请求出现异常!" + e);         e.printStackTrace();      }      return mapImags;   }//以下主要是一个uploadZip的servlet,我传的是一些图片的zip压缩,而且图图片有压缩的也有原图。主要的步骤就是在下面,精华。。。。
@WebServlet("/upload/UploadZipServlet")public class UploadZipServlet extends BaseServlet {    private static final long serialVersionUID = 1L;

    public UploadZipServlet() {        super();    }

    @Override    protected JMessage hander(HttpServletRequest request, HttpServletResponse response) {        long start = System.currentTimeMillis();        DiskFileItemFactory factory = new DiskFileItemFactory(1000 * 1024 * 1024, new File(getSystemConfig().getuTemp()));        ServletFileUpload fileUpload = new ServletFileUpload(factory);        List<FileItem> multipart = null;

        JMessage jMessage = null;        int totalCount = 0;        long userId = 0;        double validTime = 0;        try {            multipart = fileUpload.parseRequest(request);            for (FileItem item : multipart) {                if (item.isFormField()) {                    if ("validTime".equals(item.getFieldName())) {                        try {                            validTime = Double.valueOf(item.getString());                        } catch (NumberFormatException e) {                            validTime = new Double(-1);                        }                    }                    if ("userId".equals(item.getFieldName())) {                        userId = Long.parseLong(item.getString());                    }                } else {                    if (item.getSize() > 0) {                        totalCount++;                    }                }            }        } catch (Exception e) {            e.printStackTrace();        }        if (null == multipart) {            jMessage = new JMessage(1020101, "表单解析失败");        }        else if (0 == totalCount) {            jMessage = new JMessage(1010101, "缺少上传文件");        }        if (null != jMessage)            return jMessage;        jMessage = defHander(multipart, userId, validTime);

        int successCount = jMessage.getIntValue("success");        jMessage.put("total", totalCount);        jMessage.put("failure", totalCount - successCount);        jMessage.put("time", System.currentTimeMillis() - start);

        return jMessage;    }

    protected JMessage defHander(List<FileItem> multipart, long userId, double validTime) {        JMessage jMessage = null;        int successCount = 0;        String oUrl = null;        String tUrl = null;        List<UploadItem> images = Lists.newArrayList();        List<UploadItem> audios = Lists.newArrayList();        List<UploadItem> videos = Lists.newArrayList();        List<UploadItem> others = Lists.newArrayList();        for (FileItem item : multipart) {            UploadItem uploadItem;            if (item.isFormField() || item.getSize() < 1)                continue;            String oFileName = item.getName();            String formatName = ConfigUtils.getFormatName(oFileName);            String newFileName = ConfigUtils.getName(oFileName);            String fileName;            if (!StringUtils.isEmpty(newFileName) && !newFileName.equals(oFileName)) {                fileName = 32 == newFileName.length() ? oFileName : Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);            } else {                fileName = oFileName;            }         /*String fileName = 32 == ConfigUtils.getName(oFileName).length() ? oFileName : Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);*/            FileType fileType = getFileType(formatName);            File[] uploadPath = ConfigUtils.getUploadPath(userId, fileType);            File oFile = new File(uploadPath[0], fileName);            File tFile = new File(uploadPath[1], fileName);            try {                FileUtils.transfer(item.getInputStream(), oFile);                 successCount++;                 oUrl = getUrl(oFile);                 if(ConfigUtils.getSystemConfig().isOsStatus()){                    if (oUrl.contains(ConfigUtils.getSystemConfig().getDomain())){                         String urlNewName = oUrl.replace(ConfigUtils.getSystemConfig().getDomain(),"");                         String oUrlNew = FileOSUtil.uploadFile(oFile,urlNewName);                         log("UploadServlet uploadEd OBS Other oUrl"+oUrlNew);                         if (oUrlNew != null){                              oUrl = oUrlNew;                         }                   }                 }                   uploadItem = new UploadItem(oFileName, oUrl,(byte) 1, null);                   ResourcesDBUtils.saveFileUrl(1, oUrl, -1);                   others.add(uploadItem);                   log("UploadServlet uploadEd " + oUrl);                    try {                        ZipInputStream ZinO=new ZipInputStream(new FileInputStream(oFile.getPath()));                        BufferedInputStream BinO=new BufferedInputStream(ZinO);                        String ParentO=uploadPath[0].toString(); //输出路径(文件夹目录)                        File fout=null;                        ZipEntry entryO;                        try {                            while ((entryO = ZinO.getNextEntry()) != null && !entryO.isDirectory()) {                                fout = new File(ParentO, entryO.getName());                                if (!fout.exists()) {                                     (new File(fout.getParent())).mkdirs();                                 }                                FileOutputStream outO = new FileOutputStream(fout);                                BufferedOutputStream BoutO = new BufferedOutputStream(outO);                                int b;                                while ((b = BinO.read()) != -1) {                                    BoutO.write(b);                                }                                BoutO.close();                                outO.close();                                System.out.println(fout + "解压成功");                                FileInputStream fileInputStream = new FileInputStream(fout);                                MultipartFile multipartFile = new MockMultipartFile(fout.getName(), fout.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);                                images =  uploadImg(images,multipartFile,userId,validTime);                            }                            BinO.close();                            ZinO.close();                        } catch (Exception e) {                              e.printStackTrace();                        }                     } catch (FileNotFoundException e) {                        e.printStackTrace();                     }                } catch (Exception e) {                    e.printStackTrace();                    uploadItem = new UploadItem(oFileName, null, (byte) 0, e.getMessage());                    others.add(uploadItem);                }        }        Map<String, Object> data = new HashMap<String, Object>();        data.put("zip", others);        data.put("images", images);        jMessage = new JMessage(1, null, data);        jMessage.put("success", successCount);        return jMessage;

    }

    protected List<UploadItem> uploadImg(List<UploadItem> images,MultipartFile file, long userId, double validTime) {        String oUrl = null;        String tUrl = null;        String oFileName = file.getName();        String formatName = ConfigUtils.getFormatName(oFileName);        String newFileName = ConfigUtils.getName(oFileName);        String imgName;        if (!StringUtils.isEmpty(newFileName) && !newFileName.equals(oFileName)) {            imgName = 32 == newFileName.length() ? oFileName : Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);        } else {            imgName = oFileName;        }        FileType imgType = getFileType(formatName);        File[] uploadImgPath = ConfigUtils.getUploadPath(userId, imgType);        File oFile = new File(uploadImgPath[0], imgName);        File tFile = new File(uploadImgPath[1], imgName);        UploadItem uploadItem;        try {            FileUtils.transfer(file.getInputStream(), oFile, tFile, formatName);            oUrl = getUrl(oFile);            tUrl = getUrl(tFile);            if(ConfigUtils.getSystemConfig().isOsStatus()){                if (oUrl.contains(ConfigUtils.getSystemConfig().getDomain())){                    String urlNewName = oUrl.replace(ConfigUtils.getSystemConfig().getDomain(),"");                    String oUrlNew = FileOSUtil.uploadFile(oFile,urlNewName);                    log("UploadServlet uploadEd OBS oUrl "+oUrlNew);                    if (oUrlNew != null){                        oUrl = oUrlNew;                    }                }                if (tUrl.contains(ConfigUtils.getSystemConfig().getDomain())){                    String urlNewName = tUrl.replace(ConfigUtils.getSystemConfig().getDomain(),"");                    String urlNew = FileOSUtil.uploadFile(tFile,urlNewName);                    log("UploadServlet uploadEd OBS tUrl "+urlNew);                    if (urlNew != null){                        tUrl = urlNew;                    }                }            }            ResourcesDBUtils.saveFileUrl(1, oUrl, validTime);            ResourcesDBUtils.saveFileUrl(1, tUrl, validTime);            log("UploadServlet uploadEd " + oUrl);            log("UploadServlet uploadEd " + tUrl);            uploadItem = new UploadItem(oFileName, oUrl, tUrl, (byte) 1, null);        } catch (Exception e) {            e.printStackTrace();            uploadItem = new UploadItem(oFileName, null, (byte) 0, e.getMessage());        }        images.add(uploadItem);        return images;    }}

还有一个类,就是进行数据库的处理的接口首先将json string转化成json object,之后自己就可以解析啦。。。
JSONObject json = JSONObject.parseObject(zipPath);Map map = (Map)json;

原文地址:https://www.cnblogs.com/echo777/p/11311180.html

时间: 2024-11-06 07:34:59

怎样将压缩文件上传到服务器上的相关文章

C# winform把本地文件上传到服务器上,和从服务器上下载文件

昨天在做项目过程中遇到需要把本地文件上传到服务器上的问题,在这里记录一下,方便大家互相学习! /// <summary> /// 上传文件方法/// </summary> /// <param name="filePath">本地文件所在路径(包括文件)</param> /// <param name="serverPath">文件存储服务器路径(包括文件)</param> public voi

JAVA基础知识之InputStreamReader流 和 将本地文件通过前端上传到服务器上

将本地文件通过前端上传到服务器上 public BaseResponseSwagger resolveFile(@Valid @ApiParam(value = "file")@RequestParam(name = "file",required = true) MultipartFile file){ if(file.isEmpty()){ throw new SoftwareException(ComStatusCodeEnum.COM_PARAM_VALID

php form 图片上传至服务器上

本文章也是写给自己看的,因为写的很简洁,连判断都没有,只是直接实现了能上传的功能. 前台: <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="myfile" /> <input type="submit" value=

laravel上传至服务器上出现Whoops, looks like something went wrong.

1.在本地能够很好运行的laravel,上传至服务器就出现了这个问题“Whoops, looks like something went wrong.”: 2.第一步把config/app.php文件内'debug' => env('APP_DEBUG', false),改成'debug' => env('APP_DEBUG', true), 3.现在显示出了很多信息 我们注意到No supported encrypter found.The cipher and / or key lengt

php如何把文件上传到服务器上

conn.php: <?php $id=mysql_connect('localhost','root','root'); mysql_select_db("db_database12",$id); mysql_query("set names gb2312"); ?> index.php: <html> <head> <meta http-equiv="Content-Type" content=&qu

jsp项目上传到服务器

我们通过Myeclipse完成一个Java web项目时只能通过本地访问来查看,但是我们想把它上传到服务器上使用外网访问应该怎么做呢,首先肯定是要有一台服务器 个人调试项目试手的话我建议去买阿里云的云服务器,一个月才四十几块钱,购买流程我就不说了,购买网址,是要注册的哦 购买完成后阿里云会给你发邮件里面有服务器的内网以及外网的ip地址,我们就可以用外网的ip远程进入买的服务器 远程接入教程,windows下的 首先打开运行输入mstsc 计算机这一栏输入服务器的ip地址点击连接会让你输入用户名和

Android文件上传至服务器

项目演示及讲解 优酷  http://v.youku.com/v_show/id_XODk5NjkwOTg4.html 爱奇艺  http://www.iqiyi.com/w_19rs1v2m15.html#vfrm=8-7-0-1 土豆  http://www.tudou.com/programs/view/fv0H93IHfhM 项目下载 1.手机端选择文件上传至服务器端 http://download.csdn.net/detail/u010134178/8457679 2.手机端拍照上传

Myeclipse中文件已经上传到服务器目录下,文件也没有被占用,但是页面中无法读取和使用问题的解决方法

这个问题是由于Myeclipse中文件不同步引起的.在Myeclipse中,工程文件是由Myeclipse自动扫描添加的,如果在外部修改了工程目录中的文件但又关闭了自动刷新功能,则会引起文件不同步.此外,在外部没有修改Myeclipse工程中的文件也有可能引起该问题. 解决方法: 有两种解决方法: 1)手动刷新.即在Myeclipse的工程目录中,右键refresh(或者按下F5). 2)配置Myeclipse的选项: a)Myeclipse启动时,刷新workspace,即勾选:window-

java文件上传到服务器

最近项目中使用到了文件从本地到服务器的功能.其实是为了解决目前浏览器不支持获取本地文件全路径.不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持EXCEL批量导入数据. 在前台界面中 <form method="post" enctype="multipart/form-data" action="../manage/excelImport.do"> 请选文件:<input type="file&