精通Spring MVC图片处理:一个完整功能实现指南

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
一、通过指定的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);
				}

			}
		}
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Spring MVC实现图片上传功能并在页面上显示图片,可以按照以下步骤进行: 1. 配置文件上传组件。可以使用Commons FileUpload或Servlet 3.0+文件上传API。 2. 创建一个控制器方法来处理文件上传请求。该方法应该使用@RequestParam注释来获取上传的文件。 3. 在控制器方法中,将上传的文件保存到服务器文件系统上的某个位置。 4. 在控制器方法中,将文件的URL或路径存储到数据库中。 5. 创建一个JSP页面来显示存储在服务器上的图片。可以使用<img>标签来显示图片,其src属性应该是服务器上图片的URL或路径。 下面是一个示例控制器方法,用于处理文件上传请求并将文件路径存储到数据库中: ```java @RequestMapping(value = "/uploadImage", method = RequestMethod.POST) public ModelAndView uploadImage(@RequestParam("file") MultipartFile file) { //保存文件到服务器文件系统上的某个位置 String filePath = "/path/to/save/file/" + file.getOriginalFilename(); try { file.transferTo(new File(filePath)); } catch (IOException e) { e.printStackTrace(); } //将文件路径存储到数据库中 //... //返回视图 ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("imageDisplay"); modelAndView.addObject("imageUrl", filePath); return modelAndView; } ``` 然后,可以在JSP页面中使用以下代码来显示图片: ```html <img src="${imageUrl}" alt="Uploaded Image"> ``` 其中,${imageUrl}是控制器方法返回的文件路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据与后端架构提升之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值