内网环境SpringMvc前后端分离跨域高压缩上传图片整理

    关于内网服务的图片上传代码,开发细节及一些要注意的地方。

一:tomcat服务器

1.1】

修改tomcat下的web.xml

1.2】

创建upload目录用来存放图片

1.3】

tomcat放在192.168.1.108:8585,

启动tomcat,验证容器正常可用

二:java代码

2.1】

 

pom.xml添加依赖 

        <dependency>             <groupId>commons-fileupload</groupId>             <artifactId>commons-fileupload</artifactId>             <version>1.3.1</version>         </dependency>         <!-- commons-io -->         <dependency>             <groupId>commons-io</groupId>             <artifactId>commons-io</artifactId>             <version>2.4</version>         </dependency>         <dependency>             <groupId>com.sun.jersey</groupId>             <artifactId>jersey-client</artifactId>             <version>1.18.1</version>         </dependency>         <dependency>             <groupId>org.glassfish.jersey.core</groupId>             <artifactId>jersey-common</artifactId>             <version>2.0-m03</version>         </dependency>         <dependency>             <groupId>com.sun.jersey</groupId>             <artifactId>jersey-core</artifactId>             <version>1.18.1</version>

        </dependency>


2.2】

 

springmvc.xml配置文件中添加

        <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->     <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">         <!-- 指定所上传文件的总大小不能超过10M。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->         <property name="defaultEncoding" value="utf-8"/>         <property name="maxUploadSize" value="1048576"/>

    </bean>


2.3】

 

sysconfig.properties属性文件添加

#文件服务器地址 uploadHost=http://192.168.1.108:8585/ #上传的文件保存的目录 imgPath = upload/

2.4】

 

Controller层代码,消息实体自己封装

import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.sun.jersey.api.client.Client; import cn.com.onethird.common.dto.WebMessage; import cn.com.onethird.protection.common.constant.ReturnCode; import cn.com.onethird.util.ImageUtils; /**  * 上传接口  *  * @author  * @UploadController  * @date  */ @RestController public class UploadController {     @Value(value="${imgPath}")    //图片保存地址     private String imgPath;          @Value(value="${uploadHost}")     private String uploadHost;    //项目host        /**      * 上传头像      * @param request      * @param response      */     @RequestMapping(value="/upload/uploadHeadImg", method=RequestMethod.POST)     public @ResponseBody WebMessage<String> uploadSysHeadImg(HttpServletRequest request, HttpServletResponse response){         WebMessage<String> message = new WebMessage<String>();         message.setReturnCode(ReturnCode.ok.toString());         String realPath = "";         try {             MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request); //            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //            MultipartHttpServletRequest Murequest = resolver.resolveMultipart(request);                    Map<String, MultipartFile> files = multiRequest.getFileMap();             Client client = new Client();                          for(MultipartFile pic: files.values()){                 String uploadInfo = ImageUtils.upload(client, pic, request, response, uploadHost, imgPath, 200, 200);                 if(!"".equals(uploadInfo)){                     realPath = uploadInfo;//完整路径                 }             }         }catch (Exception e) {             e.printStackTrace();             message.setReturnCode(ReturnCode.fail.toString());         }         message.setMesssageBody(realPath);         return message;     } 

}

2.5】


upload工具类方法

    /**      * 上传文件--支持跨域      *      * @param request      * @param response      * @param serverPath      *            服务器地址:(http://192.168.1.121:8585/)      * @param path      *            文件路径(upload/)      * @return      */     public static String upload(Client client, MultipartFile file, HttpServletRequest request, HttpServletResponse response, String serverPath, String path) {         // 新文件名         String fileName = generateFileName(file.getOriginalFilename());         // 获取文件的扩展名         String extension = FilenameUtils.getExtension(file.getOriginalFilename());         // 相对路径         String relaPath = path + fileName;         //跨域 另一台tomcat的URL(真实路径)         String realPath = serverPath + relaPath;         // 按比例压缩图片         BufferedImage srcBufferImage = ImageIO.read(file.getInputStream());         ScaleImage scaleImage = ScaleImage.getInstance();         ByteArrayOutputStream out = new ByteArrayOutputStream();         // 如果上传图片 宽高 比 压缩的要小 则不压缩         if (w < srcBufferImage.getWidth() && h < srcBufferImage.getHeight()) {             BufferedImage scaledImage = scaleImage.imageZoomOut(srcBufferImage, w, h);             try {                 //填充out                 ImageIO.write(scaledImage, extension, out);             } catch (IOException e) {                 e.printStackTrace();             }         }         // 设置请求路径         WebResource resource = client.resource(realPath);         resource.put(String.class, out.toByteArray());         return realPath;

    }

/**      * 获得一个时间格式的新名称      *      * @param fileName      *            原图名称      * @return      */     private static String generateFileName(String fileName) {         DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");         String formatDate = format.format(new Date());         int random = new Random().nextInt(10000);         int position = fileName.lastIndexOf(".");         String extension = fileName.substring(position);         return formatDate + random + extension;

  }

2.6】

ScaleImage

  1. import java.awt.image.BufferedImage;
  2. public class ScaleImage {
  3. private int width;
  4. private int height;
  5. private int scaleWidth;
  6. private double support = (double) 3.0;
  7. private double PI = (double) 3.14159265358978;
  8. private double[] contrib;
  9. private double[] normContrib;
  10. private double[] tmpContrib;
  11. private int nDots;
  12. private int nHalfDots;
  13. /**
  14. * Start: Use Lanczos filter to replace the original algorithm for image
  15. * scaling. Lanczos improves quality of the scaled image modify by :blade
  16. */
  17. private static ScaleImage instance = new ScaleImage();
  18. private ScaleImage(){};
  19. public static ScaleImage getInstance(){
  20. return instance;
  21. }
  22. public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
  23. width = srcBufferImage.getWidth();
  24. height = srcBufferImage.getHeight();
  25. scaleWidth = w;
  26. if (DetermineResultSize(w, h) == 1) {
  27. return srcBufferImage;
  28. }
  29. CalContrib();
  30. BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
  31. BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
  32. return pbFinalOut;
  33. }
  34. /**
  35. * 决定图像尺寸
  36. */
  37. private int DetermineResultSize(int w, int h) {
  38. double scaleH, scaleV;
  39. scaleH = (double) w / (double) width;
  40. scaleV = (double) h / (double) height;
  41. if (scaleH >= 1.0 && scaleV >= 1.0) {
  42. return 1;
  43. }
  44. return 0;
  45. } // end of DetermineResultSize()
  46. private double Lanczos(int i, int inWidth, int outWidth, double Support) {
  47. double x;
  48. x = (double) i * (double) outWidth / (double) inWidth;
  49. return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
  50. / (x * PI / Support);
  51. } // end of Lanczos()
  52. //
  53. // Assumption: same horizontal and vertical scaling factor
  54. //
  55. private void CalContrib() {
  56. nHalfDots = (int) ((double) width * support / (double) scaleWidth);
  57. nDots = nHalfDots * 2 + 1;
  58. try {
  59. contrib = new double[nDots];
  60. normContrib = new double[nDots];
  61. tmpContrib = new double[nDots];
  62. } catch (Exception e) {
  63. System.out.println("init contrib,normContrib,tmpContrib" + e);
  64. }
  65. int center = nHalfDots;
  66. contrib[center] = 1.0;
  67. double weight = 0.0;
  68. int i = 0;
  69. for (i = 1; i <= center; i++) {
  70. contrib[center + i] = Lanczos(i, width, scaleWidth, support);
  71. weight += contrib[center + i];
  72. }
  73. for (i = center - 1; i >= 0; i--) {
  74. contrib[i] = contrib[center * 2 - i];
  75. }
  76. weight = weight * 2 + 1.0;
  77. for (i = 0; i <= center; i++) {
  78. normContrib[i] = contrib[i] / weight;
  79. }
  80. for (i = center + 1; i < nDots; i++) {
  81. normContrib[i] = normContrib[center * 2 - i];
  82. }
  83. } // end of CalContrib()
  84. // 处理边缘
  85. private void CalTempContrib(int start, int stop) {
  86. double weight = 0;
  87. int i = 0;
  88. for (i = start; i <= stop; i++) {
  89. weight += contrib[i];
  90. }
  91. for (i = start; i <= stop; i++) {
  92. tmpContrib[i] = contrib[i] / weight;
  93. }
  94. } // end of CalTempContrib()
  95. private int GetRedValue(int rgbValue) {
  96. int temp = rgbValue & 0x00ff0000;
  97. return temp >> 16;
  98. }
  99. private int GetGreenValue(int rgbValue) {
  100. int temp = rgbValue & 0x0000ff00;
  101. return temp >> 8;
  102. }
  103. private int GetBlueValue(int rgbValue) {
  104. return rgbValue & 0x000000ff;
  105. }
  106. private int ComRGB(int redValue, int greenValue, int blueValue) {
  107. return (redValue << 16) + (greenValue << 8) + blueValue;
  108. }
  109. private int HorizontalFilter(BufferedImage bufImg, int startX, int stopX,
  110. int start, int stop, int y, double[] pContrib) {
  111. double valueRed = 0.0;
  112. double valueGreen = 0.0;
  113. double valueBlue = 0.0;
  114. int valueRGB = 0;
  115. int i, j;
  116. for (i = startX, j = start; i <= stopX; i++, j++) {
  117. valueRGB = bufImg.getRGB(i, y);
  118. valueRed += GetRedValue(valueRGB) * pContrib[j];
  119. valueGreen += GetGreenValue(valueRGB) * pContrib[j];
  120. valueBlue += GetBlueValue(valueRGB) * pContrib[j];
  121. }
  122. valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
  123. Clip((int) valueBlue));
  124. return valueRGB;
  125. } // end of HorizontalFilter()
  126. // 图片水平滤波
  127. private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
  128. int dwInW = bufImage.getWidth();
  129. int dwInH = bufImage.getHeight();
  130. int value = 0;
  131. BufferedImage pbOut = new BufferedImage(iOutW, dwInH,
  132. BufferedImage.TYPE_INT_RGB);
  133. for (int x = 0; x < iOutW; x++) {
  134. int startX;
  135. int start;
  136. int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
  137. int y = 0;
  138. startX = X - nHalfDots;
  139. if (startX < 0) {
  140. startX = 0;
  141. start = nHalfDots - X;
  142. } else {
  143. start = 0;
  144. }
  145. int stop;
  146. int stopX = X + nHalfDots;
  147. if (stopX > (dwInW - 1)) {
  148. stopX = dwInW - 1;
  149. stop = nHalfDots + (dwInW - 1 - X);
  150. } else {
  151. stop = nHalfDots * 2;
  152. }
  153. if (start > 0 || stop < nDots - 1) {
  154. CalTempContrib(start, stop);
  155. for (y = 0; y < dwInH; y++) {
  156. value = HorizontalFilter(bufImage, startX, stopX, start,
  157. stop, y, tmpContrib);
  158. pbOut.setRGB(x, y, value);
  159. }
  160. } else {
  161. for (y = 0; y < dwInH; y++) {
  162. value = HorizontalFilter(bufImage, startX, stopX, start,
  163. stop, y, normContrib);
  164. pbOut.setRGB(x, y, value);
  165. }
  166. }
  167. }
  168. return pbOut;
  169. } // end of HorizontalFiltering()
  170. private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY,
  171. int start, int stop, int x, double[] pContrib) {
  172. double valueRed = 0.0;
  173. double valueGreen = 0.0;
  174. double valueBlue = 0.0;
  175. int valueRGB = 0;
  176. int i, j;
  177. for (i = startY, j = start; i <= stopY; i++, j++) {
  178. valueRGB = pbInImage.getRGB(x, i);
  179. valueRed += GetRedValue(valueRGB) * pContrib[j];
  180. valueGreen += GetGreenValue(valueRGB) * pContrib[j];
  181. valueBlue += GetBlueValue(valueRGB) * pContrib[j];
  182. // System.out.println(valueRed+"->"+Clip((int)valueRed)+"<-");
  183. //
  184. // System.out.println(valueGreen+"->"+Clip((int)valueGreen)+"<-");
  185. // System.out.println(valueBlue+"->"+Clip((int)valueBlue)+"<-"+"-->");
  186. }
  187. valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
  188. Clip((int) valueBlue));
  189. // System.out.println(valueRGB);
  190. return valueRGB;
  191. } // end of VerticalFilter()
  192. private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
  193. int iW = pbImage.getWidth();
  194. int iH = pbImage.getHeight();
  195. int value = 0;
  196. BufferedImage pbOut = new BufferedImage(iW, iOutH,
  197. BufferedImage.TYPE_INT_RGB);
  198. for (int y = 0; y < iOutH; y++) {
  199. int startY;
  200. int start;
  201. int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);
  202. startY = Y - nHalfDots;
  203. if (startY < 0) {
  204. startY = 0;
  205. start = nHalfDots - Y;
  206. } else {
  207. start = 0;
  208. }
  209. int stop;
  210. int stopY = Y + nHalfDots;
  211. if (stopY > (int) (iH - 1)) {
  212. stopY = iH - 1;
  213. stop = nHalfDots + (iH - 1 - Y);
  214. } else {
  215. stop = nHalfDots * 2;
  216. }
  217. if (start > 0 || stop < nDots - 1) {
  218. CalTempContrib(start, stop);
  219. for (int x = 0; x < iW; x++) {
  220. value = VerticalFilter(pbImage, startY, stopY, start, stop,
  221. x, tmpContrib);
  222. pbOut.setRGB(x, y, value);
  223. }
  224. } else {
  225. for (int x = 0; x < iW; x++) {
  226. value = VerticalFilter(pbImage, startY, stopY, start, stop,
  227. x, normContrib);
  228. pbOut.setRGB(x, y, value);
  229. }
  230. }
  231. }
  232. return pbOut;
  233. } // end of VerticalFiltering()
  234. private int Clip(int x) {
  235. if (x < 0)
  236. return 0;
  237. if (x > 255)
  238. return 255;
  239. return x;
  240. }
  241. /**
  242. * End: Use Lanczos filter to replace the original algorithm for image
  243. * scaling. Lanczos improves quality of the scaled image modify by :blade
  244. */
  245. }

2.7】

前端代码省略

常规提供一个type="file"的提交模块,后台会自动处理请求中的图片

====================================================

三:遇到的问题:

returned a response status of 403 Forbidden

需要在这个存储图片的项目所在的tomcat中配置可写操作,具体的是在Tomcat目录下的conf文件夹下的web.xml中加入

    <init-param>
        <param-name>readonly</param-name>
        <param-value>false</param-value>
    </init-param>

returned a response status of 409 Conflict

确保服务器webapps中image-web项目中存在upload路径

====================================================

由于是测试用例,主机是直接关闭了防火墙,如果需要开启防火墙还需要配置相应的出入规则

参考--

如何在局域网访问Tomcat项目

图片压缩的ScaleImage类借用http://blog.csdn.net/mmm333zzz/article/details/8569637



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值