enctype=“multipart/form-data”图片上传

package com.haiwang.tinywebsite.util;

import java.awt.image.BufferedImage;

public class ScaleImage {

        private int width;

        private int height;

        private int scaleWidth;

        private double support = (double) 3.0;

        private double PI = (double) 3.14159265358978;

        private double[] contrib;

        private double[] normContrib;

        private double[] tmpContrib;

        private int nDots;

        private int nHalfDots;

        /**
         * Start: Use Lanczos filter to replace the original algorithm for image
         * scaling. Lanczos improves quality of the scaled image modify by :blade
         */
        private static ScaleImage instance = new ScaleImage();
        private ScaleImage(){};
        public static ScaleImage getInstance(){
            return instance;
        }
        public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
            width = srcBufferImage.getWidth();
            height = srcBufferImage.getHeight();
            scaleWidth = w;

            if (DetermineResultSize(w, h) == 1) {
                return srcBufferImage;
            }
            CalContrib();
            BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
            BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
            return pbFinalOut;
        }

        /**
         * 决定图像尺寸
         */
        private int DetermineResultSize(int w, int h) {
            double scaleH, scaleV;
            scaleH = (double) w / (double) width;
            scaleV = (double) h / (double) height;
            // �?��判断�?��scaleH,scaleV,不做放大操�?
            if (scaleH >= 1.0 && scaleV >= 1.0) {
                return 1;
            }
            return 0;

        } // end of DetermineResultSize()

        private double Lanczos(int i, int inWidth, int outWidth, double Support) {
            double x;

            x = (double) i * (double) outWidth / (double) inWidth;

            return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
                    / (x * PI / Support);

        } // end of Lanczos()

        //
        // Assumption: same horizontal and vertical scaling factor
        //
        private void CalContrib() {
            nHalfDots = (int) ((double) width * support / (double) scaleWidth);
            nDots = nHalfDots * 2 + 1;
            try {
                contrib = new double[nDots];
                normContrib = new double[nDots];
                tmpContrib = new double[nDots];
            } catch (Exception e) {
                System.out.println("init   contrib,normContrib,tmpContrib" + e);
            }

            int center = nHalfDots;
            contrib[center] = 1.0;

            double weight = 0.0;
            int i = 0;
            for (i = 1; i <= center; i++) {
                contrib[center + i] = Lanczos(i, width, scaleWidth, support);
                weight += contrib[center + i];
            }

            for (i = center - 1; i >= 0; i--) {
                contrib[i] = contrib[center * 2 - i];
            }

            weight = weight * 2 + 1.0;

            for (i = 0; i <= center; i++) {
                normContrib[i] = contrib[i] / weight;
            }

            for (i = center + 1; i < nDots; i++) {
                normContrib[i] = normContrib[center * 2 - i];
            }
        } // end of CalContrib()

        // 处理边缘
        private void CalTempContrib(int start, int stop) {
            double weight = 0;

            int i = 0;
            for (i = start; i <= stop; i++) {
                weight += contrib[i];
            }

            for (i = start; i <= stop; i++) {
                tmpContrib[i] = contrib[i] / weight;
            }

        } // end of CalTempContrib()

        private int GetRedValue(int rgbValue) {
            int temp = rgbValue & 0x00ff0000;
            return temp >> 16;
        }

        private int GetGreenValue(int rgbValue) {
            int temp = rgbValue & 0x0000ff00;
            return temp >> 8;
        }

        private int GetBlueValue(int rgbValue) {
            return rgbValue & 0x000000ff;
        }

        private int ComRGB(int redValue, int greenValue, int blueValue) {

            return (redValue << 16) + (greenValue << 8) + blueValue;
        }

        // 行水平滤�?
        private int HorizontalFilter(BufferedImage bufImg, int startX, int stopX,
                                     int start, int stop, int y, double[] pContrib) {
            double valueRed = 0.0;
            double valueGreen = 0.0;
            double valueBlue = 0.0;
            int valueRGB = 0;
            int i, j;

            for (i = startX, j = start; i <= stopX; i++, j++) {
                valueRGB = bufImg.getRGB(i, y);

                valueRed += GetRedValue(valueRGB) * pContrib[j];
                valueGreen += GetGreenValue(valueRGB) * pContrib[j];
                valueBlue += GetBlueValue(valueRGB) * pContrib[j];
            }

            valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
                    Clip((int) valueBlue));
            return valueRGB;

        } // end of HorizontalFilter()

        // 图片水平滤波
        private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
            int dwInW = bufImage.getWidth();
            int dwInH = bufImage.getHeight();
            int value = 0;
            BufferedImage pbOut = new BufferedImage(iOutW, dwInH,
                    BufferedImage.TYPE_INT_RGB);

            for (int x = 0; x < iOutW; x++) {

                int startX;
                int start;
                int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
                int y = 0;

                startX = X - nHalfDots;
                if (startX < 0) {
                    startX = 0;
                    start = nHalfDots - X;
                } else {
                    start = 0;
                }

                int stop;
                int stopX = X + nHalfDots;
                if (stopX > (dwInW - 1)) {
                    stopX = dwInW - 1;
                    stop = nHalfDots + (dwInW - 1 - X);
                } else {
                    stop = nHalfDots * 2;
                }

                if (start > 0 || stop < nDots - 1) {
                    CalTempContrib(start, stop);
                    for (y = 0; y < dwInH; y++) {
                        value = HorizontalFilter(bufImage, startX, stopX, start,
                                stop, y, tmpContrib);
                        pbOut.setRGB(x, y, value);
                    }
                } else {
                    for (y = 0; y < dwInH; y++) {
                        value = HorizontalFilter(bufImage, startX, stopX, start,
                                stop, y, normContrib);
                        pbOut.setRGB(x, y, value);
                    }
                }
            }

            return pbOut;

        } // end of HorizontalFiltering()

        private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY,
                                   int start, int stop, int x, double[] pContrib) {
            double valueRed = 0.0;
            double valueGreen = 0.0;
            double valueBlue = 0.0;
            int valueRGB = 0;
            int i, j;

            for (i = startY, j = start; i <= stopY; i++, j++) {
                valueRGB = pbInImage.getRGB(x, i);

                valueRed += GetRedValue(valueRGB) * pContrib[j];
                valueGreen += GetGreenValue(valueRGB) * pContrib[j];
                valueBlue += GetBlueValue(valueRGB) * pContrib[j];
            }

            valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
                    Clip((int) valueBlue));
            return valueRGB;

        } // end of VerticalFilter()

        private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
            int iW = pbImage.getWidth();
            int iH = pbImage.getHeight();
            int value = 0;
            BufferedImage pbOut = new BufferedImage(iW, iOutH,
                    BufferedImage.TYPE_INT_RGB);

            for (int y = 0; y < iOutH; y++) {

                int startY;
                int start;
                int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);

                startY = Y - nHalfDots;
                if (startY < 0) {
                    startY = 0;
                    start = nHalfDots - Y;
                } else {
                    start = 0;
                }

                int stop;
                int stopY = Y + nHalfDots;
                if (stopY > (int) (iH - 1)) {
                    stopY = iH - 1;
                    stop = nHalfDots + (iH - 1 - Y);
                } else {
                    stop = nHalfDots * 2;
                }

                if (start > 0 || stop < nDots - 1) {
                    CalTempContrib(start, stop);
                    for (int x = 0; x < iW; x++) {
                        value = VerticalFilter(pbImage, startY, stopY, start, stop,
                                x, tmpContrib);
                        pbOut.setRGB(x, y, value);
                    }
                } else {
                    for (int x = 0; x < iW; x++) {
                        value = VerticalFilter(pbImage, startY, stopY, start, stop,
                                x, normContrib);
                        pbOut.setRGB(x, y, value);
                    }
                }

            }

            return pbOut;

        } // end of VerticalFiltering()

        private int Clip(int x) {
            if (x < 0)
                return 0;
            if (x > 255)
                return 255;
            return x;
        }

        /**
         * End: Use Lanczos filter to replace the original algorithm for image
         * scaling. Lanczos improves quality of the scaled image modify by :blade
         */

}
package com.haiwang.tinywebsite.util;

import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


/**
 *
 * 上传图片 工具类 大图片路径,生成小图片路径, 大图片文件名,生成小图片文名, 生成小图片宽度,生成小图片高度, 是否等比缩放(默认为true))
 *
 * @author Administrator
 *
 */
public class UploadUtil
{

    /**
     *
     * @param
     *
     * @param getUploadContentType
     *            文件类型
     * @param getUploadFileName
     *            原文件名
     * @return
     * @throws java.io.IOException
     */
    @SuppressWarnings("resource")
	public static String uploadImage1(HttpServletRequest request,MultipartFile file, String getUploadContentType, String getUploadFileName) throws IOException
    {
    	/**
    	 * 配置图片路径,多文件上传时不会出现
    	 * java.io.FileNotFoundException: D:\ProgramFiles\tomcat_6.0\apache-tomcat-6.0.29\apache-tomcat-6.0.29\webapps\ROOT\style\images\20141230111032905.png\20141230111057250.png
    	 * */  
    	String imagePath = "D:/ProgramFiles/tomcat_6.0/apache-tomcat-6.0.29/apache-tomcat-6.0.29/webapps/ROOT/style/images" ;
    	boolean b = false;
        File image = new File(imagePath);
        if (!image.exists())
        {
            image.mkdirs();
        }

        //判断文件的类型
        if(getUploadContentType.equals("image/gif")){
        	b = true;
        }else if(getUploadContentType.equals("image/pjpeg")){
        	b = true;
        }else if(getUploadContentType.equals("image/bmp")){
        	b = true;
        }else if(getUploadContentType.equals("image/x-png")){
        	b = true;
        }
        if(b == false){
        	return null;
        }
        // 得到文件的新名字
        String fileNewName = generateFileName(getUploadFileName);

        // 最后返回图片路径
        imagePath = imagePath + "/" + fileNewName;

        BufferedImage srcBufferImage = ImageIO.read(file.getInputStream());

        BufferedImage scaledImage;
        ScaleImage scaleImage = ScaleImage.getInstance();
        int yw = srcBufferImage.getWidth();
        int yh = srcBufferImage.getHeight();
        int w = 300, h = 300;
        // 如果上传图片 宽高 比 压缩的要小 则不压缩
        if (w > yw && h > yh)
        {
            FileOutputStream fos = new FileOutputStream(imagePath);

            ByteArrayInputStream fis = (ByteArrayInputStream) file.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0)
            {
                fos.write(buffer, 0, len);
            }
        }
        else
        {
            scaledImage = scaleImage.imageZoomOut(srcBufferImage, w, h);
            FileOutputStream out = new FileOutputStream(imagePath );
            ImageIO.write(scaledImage, "jpeg", out);
        }
        return imagePath;
    }

  

    /**
     * 传入原图名称,,获得一个以时间格式的新名称
     *
     * @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);
        return formatDate + random + ".png";
    }

}
package com.haiwang.tinywebsite.action.pc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.haiwang.entity.Drugs;
import com.haiwang.entity.Manual;
import com.haiwang.entity.Medicine;
import com.haiwang.tinywebsite.biz.TinywebsiteMedicineBiz;
import com.haiwang.tinywebsite.util.UploadUtil;
import com.haiwang.util.JsonWriteUtil;


@org.springframework.stereotype.Controller(value = "tinywebsitePcMedicineController")
@RequestMapping(value = "/medicine_pc")
@Scope(value="prototype")
public class TinywebsitePcMedicineController implements Controller{
	@Resource(name="tinywebsiteMedicineBiz")
	private TinywebsiteMedicineBiz medicineBiz;

	public ModelAndView handleRequest(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		return null;
	}
	
	//商品列表 
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/goodsMedicineList_pc")
	public ModelAndView goodsMedicine(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		List<Map> listMedicine = medicineBiz.selectAllMedicine(); 
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("rows",listMedicine);
		jsonMap.put("total",listMedicine.size());
		JsonWriteUtil.writeJson(arg1, jsonMap);  
		return  null;
	}
	
	//商品详情、到修改页面
	@RequestMapping(value = "/goodsMedicineDetails_pc")
	public ModelAndView goodsMedicineDetails(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		String id = arg0.getParameter("id");
		Medicine medicine = medicineBiz.selectByPrimaryKey(Integer.parseInt(id));
		List<Drugs> drugs = medicineBiz.selectAllDrugs();
		List<Manual> manual = medicineBiz.selectAllManual();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("med",medicine);
		map.put("drugs",drugs);
		map.put("manual",manual);
		return new ModelAndView("tinywebsite_pc/medicine/medicine_add",map);
	}
	
	//到添加商品页
	@RequestMapping(value = "/toGoodsMedicine_pc")
	public ModelAndView toGoodsMedicine(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		List<Drugs> drugs = medicineBiz.selectAllDrugs();
		List<Manual> manual = medicineBiz.selectAllManual();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("drugs",drugs);
		map.put("manual",manual);
		return new ModelAndView("tinywebsite_pc/medicine/medicine_add",map);
	}
	
	//添加
	@RequestMapping(value = "/goodsMedicineSave_pc", method=RequestMethod.POST)
	public ModelAndView saveMedicine(HttpServletRequest arg0, HttpServletResponse arg1,
			@RequestParam(value="imgpath", required=false)MultipartFile imgpath,
			@RequestParam(value="detailspath", required=false) MultipartFile detailspath) throws Exception {
		String name = ZMStringTest(arg0.getParameter("name"));
		String commoditynumber = ZMStringTest(arg0.getParameter("commoditynumber"));
		String specifications = ZMStringTest(arg0.getParameter("specifications"));
		String factory = ZMStringTest(arg0.getParameter("factory"));
		String oldprice = ZMStringTest(arg0.getParameter("oldprice"));
		String newprice = ZMStringTest(arg0.getParameter("newprice"));
		String introduction = ZMStringTest(arg0.getParameter("introduction"));
		String drugsid = ZMStringTest(arg0.getParameter("drugsid"));
		String manualid = ZMStringTest(arg0.getParameter("manualid"));
		String imgpathName = null;
		String imgpathStr = null;
		String detailspathName = null;
		String detailspathStr = null;
		if(imgpath != null && imgpath.getOriginalFilename()!=null&&!imgpath.getOriginalFilename().equals("")){
			imgpathName = imgpath.getOriginalFilename();
		}
		if(imgpathName != null&&!imgpathName.equals("")){
			imgpathStr = UploadUtil.uploadImage1(arg0, imgpath, imgpath.getContentType(), imgpathName);
		}
		if(detailspath != null && detailspath.getOriginalFilename()!=null&&!detailspath.getOriginalFilename().equals("")){
			detailspathName = imgpath.getOriginalFilename();
		}
		if(detailspathName != null&&!detailspathName.equals("")){
			detailspathStr = UploadUtil.uploadImage1(arg0, detailspath, detailspath.getContentType(), detailspathName);
		}
	   saveOrupdate(imgpathStr, detailspathStr, null, name, commoditynumber, specifications, factory, oldprice, newprice, introduction, drugsid, manualid);
	   return new ModelAndView("redirect:/medicine_pc/toGoodsMedicine_pc");
	}
	
	//修改
	@RequestMapping(value = "/goodsMedicineUpdate_pc")
	public ModelAndView updateMedicine(HttpServletRequest arg0, HttpServletResponse arg1,
			@RequestParam(value="imgpath", required=false)MultipartFile imgpath,
			@RequestParam(value="detailspath", required=false) MultipartFile detailspath) throws Exception {
		String strId = ZMStringTest(arg0.getParameter("id"));
		String name = ZMStringTest(arg0.getParameter("name"));
		String commoditynumber = ZMStringTest(arg0.getParameter("commoditynumber"));
		String specifications = ZMStringTest(arg0.getParameter("specifications"));
		String factory = ZMStringTest(arg0.getParameter("factory"));
		String oldprice = ZMStringTest(arg0.getParameter("oldprice"));
		String newprice = ZMStringTest(arg0.getParameter("newprice"));
		String introduction = ZMStringTest(arg0.getParameter("introduction"));
		String drugsid = ZMStringTest(arg0.getParameter("drugsid"));
		String manualid = ZMStringTest(arg0.getParameter("manualid"));
		String imgpathName = null;
		String imgpathStr = null;
		String detailspathName = null;
		String detailspathStr = null;
		if(imgpath != null && imgpath.getOriginalFilename()!=null&&!imgpath.getOriginalFilename().equals("")){
			imgpathName = imgpath.getOriginalFilename();
		}
		if(imgpathName != null&&!imgpathName.equals("")){
			imgpathStr = UploadUtil.uploadImage1(arg0, imgpath, imgpath.getContentType(), imgpathName);
		}
		if(detailspath != null && detailspath.getOriginalFilename()!=null&&!detailspath.getOriginalFilename().equals("")){
			detailspathName = imgpath.getOriginalFilename();
		}
		if(detailspathName != null&&!detailspathName.equals("")){
			detailspathStr = UploadUtil.uploadImage1(arg0, detailspath, detailspath.getContentType(), detailspathName);
		}
		saveOrupdate(imgpathStr, detailspathStr, strId, name, commoditynumber, specifications, factory, oldprice, newprice, introduction, drugsid, manualid);
		return new ModelAndView("redirect:/medicine_pc/goodsMedicineDetails_pc?id="+strId);
	}
	
	public void saveOrupdate(String imgpath,String detailspath, String id,String name,String commoditynumber,String specifications,
			String factory,String oldprice,String newprice,String introduction,String drugsid,String manualid) {
		try{
			Medicine medicine = new Medicine();
			medicine.setName(name);
			medicine.setCommoditynumber(commoditynumber);
			medicine.setSpecifications(specifications);
			medicine.setFactory(factory);
			medicine.setIntroduction(introduction);
			if(oldprice != null){
				medicine.setOldprice(Double.valueOf(newprice));
			}else{
				medicine.setOldprice(0.0);
			}
			
			if(newprice != null){
				medicine.setNewprice(Double.valueOf(newprice));
			}else{
				medicine.setNewprice(0.0);
			}
			
			if(imgpath != null){
				medicine.setImgpath(imgpath);
			}
			
			if(detailspath != null){
				medicine.setDetailspath(detailspath);
			}
			
			if(drugsid != null){
				medicine.setDrugsid(Integer.parseInt(drugsid));
			}else{
				medicine.setDrugsid(1);
			}
			
			if(manualid != null){
				medicine.setManualid(Integer.parseInt(manualid));
			}else{
				medicine.setManualid(1);
			}
			if(id!= null){
				medicine.setId(Integer.parseInt(id));
				medicineBiz.updateMedicine(medicine);//修改
				
			}else{
			   medicineBiz.saveMedicine(medicine);//保存
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//删除
	@RequestMapping(value = "/deleteMedicine_pc")
	public ModelAndView deleteMedicine(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		String strId = arg0.getParameter("id");
		if(strId != null){
			Integer id = Integer.parseInt(strId);
			medicineBiz.deleteMedicine(id);
		}
		
		return new ModelAndView("tinywebsite_pc/medicine/medicine_mall");
	}
	
	
	 //转码的方法
    public String ZMStringTest(String str){
        String strTest=null;
        String temp=getEncodingString(str);
        if(temp.equals("UTF-8"))
        {
            strTest=str;

        }
        else if(temp.equals("ISO-8859-1")){
            try{
                strTest=new String(str.getBytes("ISO8859-1"), "UTF-8");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return strTest;
    }
    // 判断字符串的编码
    public static String getEncodingString(String str) {
        String encode = "GB2312";
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode)) ) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        return "";
    }
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>药品管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript" src="common/js/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="common/js/easyui/jquery.easyui.min.js"></script>
<link rel="stylesheet" type="text/css" href="common/css/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="common/css/easyui/themes/icon.css">
<script type="text/javascript"	src="common/js/easyui/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
function checkAll(){
	var name = document.getElementById("name").value;
	var commoditynumber = document.getElementById("commoditynumber").value;
	var specifications = document.getElementById("specifications").value;
	var factory = document.getElementById("factory").value;
	var oldprice = document.getElementById("oldprice").value;
	var newprice = document.getElementById("newprice").value;
	var introduction = document.getElementById("introduction").value;
	var pricematch = /^(?:[\+\-]?\d+(?:\.\d+)?|\.\d*?)?$/;//数字匹配,小数点、整数
	var specificationsmatch = /^[A-Za-z0-9]+$/;//数字、字母匹配
	var commoditynumbermatch = /^[1-9]\d*$/;//正整数匹配
	var detailspath = document.getElementById("detailspath").value;//药品详情图片
	var imgpath = document.getElementById("imgpath").value;//药品图片
	if(name==""){
		alert("药品名称不能为空!");
		return false;
	}
	if(commoditynumber==""){
		alert("药品编号不能为空!");
		return false;
	}else{
		if(!commoditynumbermatch.test(commoditynumber)){
			alert("药品编号只能输入数字!");
			return false;
		}
	}
	if(specifications==""){
		alert("药品规格不能为空!");
		return false;
	}else{
		if(!specificationsmatch.test(specifications)){
			alert("药品规格只能输入字母和数字!");
			return false;
		}
	}
	if(factory==""){
		alert("药品生产厂家不能为空!");
		return false;
	}
	
	if(!pricematch.test(oldprice)){
		alert("只能输入数字!允许有小数点。");
		return false;
	}


	if(!pricematch.test(newprice)){
		alert("只能输入数字!允许有小数点。");
		return false;
	}
	
	if(introduction == ""){
		alert("药品简介不能为空!");
		return false;
	}
	if(checkFileType(detailspath,"药品详情图片") == false){
		return false;
	}
	if(checkFileType(imgpath,"药品图片") == false){
		return false;
	}
}

function checkFileType(filename,img){
	if(filename != ""){
		if(filename.lastIndexOf(".")!=-1)  
		{  
			var fileType = (filename.substring(filename.lastIndexOf(".")+1,filename.length)).toLowerCase();  
			var suppotFile = new Array();  
			suppotFile[0] = "gif";  
			suppotFile[1] = "bmp";  
			suppotFile[2] = "jpg";  
			suppotFile[2] = "png";  
			for(var i =0;i<suppotFile.length;i++){  
				if(suppotFile[i]==fileType){  
			     	return true;  
				}else{  
			     	continue;  
				}  
			}  
		    alert(img+"不支持文件类型"+fileType);  
	    	return false;  
		}else {  
		    alert("文件只支持JIF,BMP,JPG,PNG");  
		}  
	}
}
</script>
</head>

<body>

	<form action='${pageContext.request.contextPath}${med==null?"/medicine_pc/goodsMedicineSave_pc":"/medicine_pc/goodsMedicineUpdate_pc"}'
	 method="POST" enctype="multipart/form-data" onsubmit="return checkAll()">
	<table border="0" style="position:absolute;left:260px;top:10px;">
	   <tr>
	   	<th>&nbsp;</th>
	   	<td> <input type="hidden" name="id" value="${med.id}"/></td>
	   </tr>
		<tr>
			<th>药品名称</th>
			<td >
			   <input type="text" name="name" value="${med.name}"/>
			</td>
		</tr>
		<tr>
			<th>药品编号</th>
			<td ><input type="text" name="commoditynumber" value="${med.commoditynumber}"/></td>
		</tr>
		<tr>
			<th>药品规格</th>
			<td ><input type="text" name="specifications" value="${med.specifications}"/></td>
		</tr>
		<tr>
			<th>生产厂家</th>
			<td ><input type="text" name="factory" value="${med.factory}"/></td>
		</tr>
		<tr>
			<th>原价</th>
			<td ><input type="text" name="oldprice" value="${med.oldprice}"/></td>
		</tr>
		<tr>
			<th>折后价</th>
			<td ><input type="text" name="newprice" value="${med.newprice}"/></td>
		</tr>
		<tr>
			<th>药品简介</th>
			<td><textarea rows="10" cols="50" name="introduction">${med.introduction}</textarea></td>
		</tr>
		<tr>
			<th>药品图片</th>
			<td>
			   <c:if test="${med.imgpath!=null }"><img src="${med.imgpath}"></c:if>
			   <input type="file" value="上传图片" name="imgpath" id="imgpath">&nbsp;<font size="2" color="red">图片小于200k,格式:jpg、gif、png、bmp</font>
			</td>
		</tr>
		<tr>
			<th>药品详情图片</th>
			<td>
			    <c:if test="${med.detailspath!=null }"><img src="${med.detailspath}"></c:if>
			    <input type="file" value="上传图片" name="detailspath" id="detailspath">&nbsp;<font size="2" color="red">图片小于200k,格式:jpg、gif、png、bmp</font>
			</td>
		</tr>
		<tr>
			<th>药品大类</th>
			<td><select name="drugsid" onchange="selectDrugs(this)">
					<c:forEach items="${drugs}" var="drugs">
						<option <c:if test="${drugs.id ==  med.drugsid}">selected</c:if> value="${drugs.id}" >${drugs.name}</option>
					</c:forEach>
			</select>
			</td>
		</tr>
		<tr>
			<th>药品说明书</th>
			<td><select name="manualid" onchange="selectManual(this)">
					<c:forEach items="${manual}" var="mau">
						<option <c:if test="${mau.id ==  med.manualid}">selected</c:if> value="${mau.id}">${mau.tradename}</option>
					</c:forEach>
			</select>
			</td>
		</tr>
		<tr>
			<td colspan="2" style="text-align:center;"><input type="submit"  value="  提   交   ">&nbsp;&nbsp;&nbsp;&nbsp;
			 <input type="button" name="submit" onclick="javascript:history.back(-1);" value="  返    回  ">
			</td>
		</tr>
	</table>
	</form>
	
</body>
</html>

web.xml 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>haiwang</display-name>
	<filter>
		<filter-name>CharEncoding</filter-name>
		<filter-class>com.haiwang.filter.CharEncoding</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>CharEncoding</filter-name>
		<url-pattern>/homeInfoCountServlet</url-pattern>
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:com/haiwang/config/applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:com/haiwang/config/springmvc-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.js</url-pattern>
		<url-pattern>*.htm</url-pattern>
		<url-pattern>*.css</url-pattern>
		<url-pattern>*.json</url-pattern>
		<url-pattern>*.gif</url-pattern>
		<url-pattern>*.jpg</url-pattern>
		<url-pattern>*.png</url-pattern>
	</servlet-mapping>

</web-app>

 springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd  
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
	http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
	http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- 让Spring支持注解 -->
	<context:component-scan base-package="*"></context:component-scan>

	<!-- 默认的注解映射的支持 -->
	<mvc:annotation-driven />

	<!-- 对静态资源的访问 -->
	<mvc:resources mapping="common/**" location="/common/" />


	<!-- HandlerMapping -->
	<bean
		class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
	<!-- HandlerAdapter -->
	<bean
		class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView"></property>

		<!--配置的是前缀 -->
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8" />
		<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
		<property name="maxUploadSize" value="20000000" />
	</bean>
	<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
	<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
	<bean id="exceptionResolver"
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
				<prop
					key="org.springframework.web.multipart.MaxUploadSizeExceededException">tinywebsite_pc/file_upload/error_fileupload</prop>
			</props>
		</property>
	</bean>
</beans>

猜你喜欢

转载自1160514291.iteye.com/blog/2171288