SpringMVC项目图片处理功能总结

简介: SpringMVC项目图片处理功能总结

一、通过指定的url获取页面的html

public static String findHtmlStringByURL(String HTML_URL) throws IOException {
        try {
            StringBuffer html = new StringBuffer();
            URL url = new URL(HTML_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStreamReader isr = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            String temp;
            while ((temp = br.readLine()) != null) {
                 html.append(temp).append("\n");
            }
            br.close();
            isr.close();
            return html.toString().getBytes("GBK"), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

1.为了避免中文乱码,需要实现指定jsp页面的编码为utf-8,但是如果遇到html页面的特殊标签可能会产生一些部分中文乱码

更好的解决方案可以用jsonp

public static String findHtmlStringByURL(String HTML_URL) throws IOException {
      URL url = new URL(HTML_URL);
        Document document=Jsoup.parse(url,5 * 1000);
        String result=document.html();
        //解决img标签结尾无斜杠(/)的问题
        String regex = "(?i)(\\<img)([^\\>]+)(\\>)";
        String value =  result.replaceAll(regex, "$1 $2 /$3");
        return value;
    }

maven坐标如下:

<dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.8.1</version>
        </dependency>

URL url = new URL(HTML_URL);
 URL模拟http请求获取不到session

二、SpringMVC框架里jsp客户端向服务端传递List类型的参数

客户端

//传递数组partListDesignArray 到服务端
                       var partListDesignArray = new Array();
                             var listTrEdit=$("#container").find("tr.nowCheck");
                $.each(listTrEdit, function(n,value){
                var partsno=$(value).find("input#partsno").val();
                var partsid=$(value).find("input#partsid").val();
                var partsname=$(value).find("input#partsname").val();
                var material=$(value).find("input#material").val();
                var num=$(value).find("input#num").val();
                var price=$(value).find("input#price").val()*100;
                var provider=$(value).find("input#provider").val();
                var comment=$(value).find("input#comment").val();
                            partListDesignArray.push({
                            id: partsid, partsname: partsname,                           
                           partsno:partsno,material:material, 
                            num:num,price:price,provider:provider,comment:comment});
                 });
                       $.ajax({
                            url:   CONTEXT_PATH+'front/carDesign/saveEditPart',
                            type:  "POST",
                            contentType : 'application/json;charset=utf-8', //设置请求头信息
                            dataType:"json",
                            data:  JSON.stringify(partListDesignArray),            
                            success: function(data){
                                if(data.result){
                                    if(type==1){
                                        window.location.href=CONTEXT_PATH+'front/carDesign/carDesign_list';
                                    }else{
                                        window.location.reload();
                                    }
                                }else{
                                    jAlert(data.msg,'提示');
                                }
                            }
                      });

服务端

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
    @RequestMapping("/saveEditPart")
    @ResponseBody
    public AjaxObj saveEditPart(@RequestBody  List<JSONObject> partListDesignModels){
        AjaxObj  ajaxObj= partListDesignService.saveEditPart(partListDesignModels);
        return ajaxObj;
    }

接收list数据

三.SpringMVC中的文件下载

package com.clj.test.down.util;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author  Administrator
 * @version  [版本号, 2014年3月7日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@Component
@Scope("prototype")
@RequestMapping("/downloadFile")
public class DownloadAction
{
    @RequestMapping("download")  
    public ResponseEntity<byte[]> download() throws IOException {  
        String path="D:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\springMVC\\WEB-INF\\upload\\图片10(定价后).xlsx";
        File file=new File(path);
        HttpHeaders headers = new HttpHeaders();  
        String fileName=new String("你好.xlsx".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),  
                                          headers, HttpStatus.CREATED);  
    }  
}

四、基于iText和flying saucer结合freemark把html生成pdf (支持css样式)

项目地址:http://git.oschina.net/lemonzone2010/doc-render

尝试了几个开源项目感觉这个效果最好,而且文旦详尽,需要注意的是

1、不支持css3特殊样式,html里如果有中文需要现在css样式里申明所用字体

2、项目里读取html时使用了freemark技术也但是我自己操作的时候利用总结一里的jsonp读取更加方便

五、把文件打包生成zip

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
 * Zip文件工具类
 * @author Luxh
 */
public class ZipUtil {
    /**
     * 把文件压缩成zip格式
     * @param files         需要压缩的文件
     * @param zipFilePath 压缩后的zip文件路径   ,如"D:/test/aa.zip";
     */
    public static void compressFilesToZip(File[] files,String zipFilePath,String[]filename) {
        if(files != null && files.length >0) {
            if(isEndsWithZip(zipFilePath)) {
                ZipArchiveOutputStream zaos = null;
                try {
                    File zipFile = new File(zipFilePath);
                    zaos = new ZipArchiveOutputStream(zipFile);
                    //Use Zip64 extensions for all entries where they are required
                    zaos.setUseZip64(Zip64Mode.AsNeeded);
                    //将每个文件用ZipArchiveEntry封装
                    //再用ZipArchiveOutputStream写到压缩文件中
                    for(int i=0;i<files.length;i++) {
                      File file=files[i];
                        if(file != null) {
                            ZipArchiveEntry zipArchiveEntry  = new ZipArchiveEntry(file,filename[i]);
                            zaos.putArchiveEntry(zipArchiveEntry);
                            InputStream is = null;
                            try {
                                is = new BufferedInputStream(new FileInputStream(file));
                                byte[] buffer = new byte[1024 * 5]; 
                                int len = -1;
                                while((len = is.read(buffer)) != -1) {
                                    //把缓冲区的字节写入到ZipArchiveEntry
                                    zaos.write(buffer, 0, len);
                                }
                                //Writes all necessary data for this entry.
                                zaos.closeArchiveEntry(); 
                            }catch(Exception e) {
                                throw new RuntimeException(e);
                            }finally {
                                if(is != null)
                                    is.close();
                            }
                        }
                    }
                    zaos.finish();
                }catch(Exception e){
                    throw new RuntimeException(e);
                }finally {
                        try {
                            if(zaos != null) {
                                zaos.close();
                            }
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                }
            }
        }
    }
    /**
     * 把zip文件解压到指定的文件夹
     * @param zipFilePath   zip文件路径, 如 "D:/test/aa.zip"
     * @param saveFileDir   解压后的文件存放路径, 如"D:/test/"
     */
    public static void decompressZip(String zipFilePath,String saveFileDir) {
        if(isEndsWithZip(zipFilePath)) {
            File file = new File(zipFilePath);
            if(file.exists()) {
                InputStream is = null;
                //can read Zip archives
                ZipArchiveInputStream zais = null;
                try {
                    is = new FileInputStream(file);
                    zais = new ZipArchiveInputStream(is);
                    ArchiveEntry  archiveEntry = null;
                    //把zip包中的每个文件读取出来
                    //然后把文件写到指定的文件夹
                    while((archiveEntry = zais.getNextEntry()) != null) {
                        //获取文件名
                        String entryFileName = archiveEntry.getName();
                        //构造解压出来的文件存放路径
                        String entryFilePath = saveFileDir + entryFileName;
                        byte[] content = new byte[(int) archiveEntry.getSize()];
                        zais.read(content);
                        OutputStream os = null;
                        try {
                            //把解压出来的文件写到指定路径
                            File entryFile = new File(entryFilePath);
                            os = new BufferedOutputStream(new FileOutputStream(entryFile));
                            os.write(content);
                        }catch(IOException e) {
                            throw new IOException(e);
                        }finally {
                            if(os != null) {
                                os.flush();
                                os.close();
                            }
                        }
                    }
                }catch(Exception e) {
                    throw new RuntimeException(e);
                }finally {
                        try {
                            if(zais != null) {
                                zais.close();
                            }
                            if(is != null) {
                                is.close();
                            }
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                }
            }
        }
    }
    /**
     * 判断文件名是否以.zip为后缀
     * @param fileName        需要判断的文件名
     * @return 是zip文件返回true,否则返回false
     */
    public static boolean isEndsWithZip(String fileName) {
        boolean flag = false;
        if(fileName != null && !"".equals(fileName.trim())) {
            if(fileName.endsWith(".ZIP")||fileName.endsWith(".zip")){
                flag = true;
            }
        }
        return flag;
    }

六、图片上传到非工程文件夹下,希望通过该工程的url访问该图片

文件上传到tomcat下的工程下,项目重新启动图片就没了

解决的思路:

在配置文件下配置路径

BASE_FILEUPLOAD_URL=/upload/username/type/year/month/

BASE_FILEUPLOAD_PATH=…/…/upload/username/type/year/month/

上传文件时读取该路径并进行拼接:

//文件上传目录路径

String savePath = pageContext.getServletContext().getRealPath("/") + BASE_FILEUPLOAD_PATH;

这样配置以后图片就上传到tomcat的一级目录下了

定义访问的时候url为localhost:8080//btkjsite_designcloud/before/getFile/upload/username/type/year/month/20160911.jpg

先根据访问的url找到图片的实际物理路径,再通过输入流读取文件,写入输出流在网页上把图片显示出来

package com.meila.cms.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import com.meila.cms.util.config.Property;
@Controller
@RequestMapping("/before")
public class FileController extends BaseController{
  /**
   * 由于kindeditor文件保存在其他文件夹下所以以流的形式重新进行访问
   * @param dirname
   * @param username
   * @param type
   * @param year
   * @param month
   * @param picname
   * @param extname
   */
  @RequestMapping(value="/getFile/{dirname}/{username}/{type}/{year}/{month}/{picname}.{extname}")
  public void getFile(@PathVariable String dirname,
      @PathVariable String username,@PathVariable String type,
      @PathVariable String year,@PathVariable String month,
      @PathVariable String picname,@PathVariable String extname){
      String BASE_FILEUPLOAD_PATH= Property.getProperty("BASE_FILEUPLOAD_PATH");
      WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();  
        ServletContext application = webApplicationContext.getServletContext();
    String web_path = application.getRealPath("").replace("\\", "/");
        BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("username",username);
      BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("type", "A0");
      BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("year", year);
      BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("month",month);
    String fullPath = web_path+"/"+BASE_FILEUPLOAD_PATH +picname+"."+extname;
    response.setHeader("Cache-Control", "max-age=10000000");
    InputStream in = null;
    OutputStream out = null;
    try {
      File file = new File(fullPath);
      if (!file.isFile()) {
      }
      in = new FileInputStream(file);
      int len = 0;
      byte[] buffer = new byte[1024];
      out = response.getOutputStream();
      while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
}


相关文章
|
6月前
|
Java 数据库连接 数据库
SpringMVC之增删改查(CRUD)项目模拟
SpringMVC之增删改查(CRUD)项目模拟
58 0
|
8月前
|
XML JSON 前端开发
SpringMVC运行项目出现The request sent by the client was syntactically incorrect.问题解决思路?
使用SpringMVC报HTTP Status 400 - The request sent by the client was syntactically incorrect.的错误怎么解决,你不妨看一下我的这个解决思路,再决定,往往你最忽略的地方就是你最容易报错的地方,所以我建议你看一看我的这个思路是否与你的问题一样
|
4月前
|
前端开发 Java Apache
JAVAEE框架技术之6-springMVC拦截器和文件上传功能
JAVAEE框架技术之6-springMVC拦截器和文件上传功能
72 0
JAVAEE框架技术之6-springMVC拦截器和文件上传功能
|
2月前
SpringMVC跳转外部项目方式
SpringMVC跳转外部项目方式
10 0
|
2月前
|
移动开发 Java 测试技术
Spring MVC+Spring+Mybatis实现支付宝支付功能(附完整代码)
Spring MVC+Spring+Mybatis实现支付宝支付功能(附完整代码)
22 1
|
4月前
|
JSON 前端开发 Java
Spring MVC响应结合RESTful风格开发,打造具有强大功能和良好体验的Web应用!
Spring MVC响应结合RESTful风格开发,打造具有强大功能和良好体验的Web应用!
|
4月前
|
前端开发 Java Maven
SpringMVC之初识SpringMVC和项目创建
【1月更文挑战第18天】 一、SpringMVC简介 1、什么是MVC 2、什么是SpringMVC 3、SpringMVC的特点 二、SpringMVC项目创建步骤 1、创建maven工程 a>添加web模块 b>打包方式:war c>引入依赖 2、配置web.xml a>默认配置方式 b>扩展配置方式 3、创建请求控制器 4、创建springMVC的配置文件 5、测试HelloWorld a>实现对首页的访问 b>通过超链接跳转到指定页面
59 0
|
5月前
|
XML Java 应用服务中间件
SpringMVC与Servlet3.0整合 - ServletContainerInitializer注解配置项目
SpringMVC与Servlet3.0整合 - ServletContainerInitializer注解配置项目
23 1
|
6月前
|
Java 应用服务中间件 开发工具
搭建spring+springmvc项目
搭建spring+springmvc项目
36 0
|
8月前
|
消息中间件 前端开发 Java
GitHub标星30k!基于Spring MVC Mybatis分布式开发系统-zheng项目
zheng项目不仅仅是一个开发架构,而是努力打造一套从 前端模板 - 基础框架 - 分布式架构 - 开源项目 - 持续集成 - 自动化部署 - 系统监测 - 无缝升级 的全方位J2EE企业级开发解决方案。