以前做项目也没用过多线程,这次项目里要求的多个图片上传功能,自己觉得学着用多线程来写可能会好些,些的很简陋,请拍砖!正题如下:

1.导包(不说了,反正要spring mvc包,common.io,common-uploade这些包和jqury.form.js等js包)

2.jsp页面:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 <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">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.form.js"></script>
</head>
<body>
<div id="Layer1">
图片1:
<ul>
  <img src="${pageContext.request.contextPath}/p_w_picpaths/loading.gif" id="imgidmainImg" style="display:none;"></img>
   <form action="${pageContext.request.contextPath}/admin/ajaximg" enctype="multipart/form-data" method="post" id="uploadImgFormmainImg">
 <input id="imgInputmainImg" type="file" name="photo" value="上传" />
 <input type="button" class="imgSave" value="确定" />
 <input type="hidden" value="mainImg"></input>
</form><br><br><br><br>
图片2:
  <img src="${pageContext.request.contextPath}/p_w_picpaths/loading.gif" id="imgidgoodsp_w_picpath2" style="display:none;"></img>
   <form action="${pageContext.request.contextPath}/admin/ajaximg" enctype="multipart/form-data" method="post" id="uploadImgFormgoodsp_w_picpath2">
 <input id="imgInputgoodsp_w_picpath2" type="file" name="photo" value="上传" />
 <input type="button" class="imgSave" value="确定" />
 <input type="hidden" value="goodsp_w_picpath2"></input>
</form>
<br><br><br><br>
图片3:
  <img src="${pageContext.request.contextPath}/p_w_picpaths/loading.gif" id="imgidgoodsp_w_picpath3" style="display:none;"></img>
   <form action="${pageContext.request.contextPath}/admin/ajaximg" enctype="multipart/form-data" method="post" id="uploadImgFormgoodsp_w_picpath3">
 <input id="imgInputgoodsp_w_picpath3" type="file" name="photo" value="上传" />
 <input type="button" class="imgSave" value="确定" />
 <input type="hidden" value="goodsp_w_picpath3"></input>
</form>
<br><br><br><br>
图片4:
  <img src="${pageContext.request.contextPath}/p_w_picpaths/loading.gif" id="imgidgoodsp_w_picpath4" style="display:none;"></img>
   <form action="${pageContext.request.contextPath}/admin/ajaximg" enctype="multipart/form-data" method="post" id="uploadImgFormgoodsp_w_picpath4">
 <input id="imgInputgoodsp_w_picpath4" type="file" name="photo" value="上传" />
 <input type="button" class="imgSave" value="确定" />
 <input type="hidden" value="goodsp_w_picpath4"></input>
</form>
<br><br><br><br>
图片5:
  <img src="${pageContext.request.contextPath}/p_w_picpaths/loading.gif" id="imgidgoodsp_w_picpath5" style="display:none;"></img>
   <form action="${pageContext.request.contextPath}/admin/ajaximg" enctype="multipart/form-data" method="post" id="uploadImgFormgoodsp_w_picpath5">
 <input id="imgInputgoodsp_w_picpath5" type="file" name="photo" value="上传" />
 <input type="button" class="imgSave" value="确定" />
 <input type="hidden" value="goodsp_w_picpath5"></input>
</form>
</div>
</body>
<script type="text/javascript">
 $(document).ready(function() { 
  /* 图片上传 */
  $(".imgSave").click(function(){
   var objhid = $(this).next().val();
   if ($("#imgInput"+objhid).val() == "") {
    alert("please select a p_w_picpath to upload!");
    return;
   }
   $("#imgid"+objhid).css("display","block");
   $("#uploadImgForm"+objhid).ajaxSubmit({
       success: function (html, status) {  
        html = html.replace("<PRE>", "").replace("</PRE>", "");
        $("#imgid"+objhid).attr('src', "${pageContext.request.contextPath}"+html);        
    }
   });
   $("#imgInput"+objhid).val("");
   return false; 
  }); 
 });
</script>
</html>

3.action代码:

 /**
  * jquery.form.js异步上传图片(多个图片)
  * @param request
  * @param response
  * @return
  */
 @RequestMapping(value = "ajaximg", method = RequestMethod.POST)
 public String ajaxGoodsImg(MultipartHttpServletRequest request,
   HttpServletResponse response) {
  PrintWriter out = null;
  try {
   response.setContentType("text/plain;charset=UTF-8");
   // 以下两句为取消在本地的缓存
   out = response.getWriter();
   MultipartFile p_w_picpathfile = request.getFile("photo");
   HttpSession session = request.getSession();
   String flag = null;
   if (null != p_w_picpathfile && 0 != p_w_picpathfile.getSize()) {
    byte[] b = p_w_picpathfile.getBytes();
    InputStream input = p_w_picpathfile.getInputStream();
    String fileNameLong = p_w_picpathfile.getOriginalFilename();
    FileUploadThread uploadthread = new FileUploadThread(session.getServletContext().getRealPath(""),
      fileNameLong,input,b);
    uploadthread.start();uploadthread.join();flag = uploadthread.getReturnStr();
      if (flag == "false") {out.print("falsemsg");} else { out.print(flag);  } }
  } catch (Exception e) {e.printStackTrace();} finally {if (out != null) {  out.close(); }} return null;}

4.多线程上传工具类:

import java.awt.p_w_picpath.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;import javax.p_w_picpathio.ImageIO;

/**
 * 多线程 图片上传功能
 */
public class FileUploadThread extends Thread implements Serializable{ private static final long serialVersionUID = 7383841520335606068L;
 private String fileRealPath;
 private String fileNameLong;
 private InputStream input;
 private byte[] b;
  String returnStr;
 public FileUploadThread(String fileRealPath, String fileNameLong, InputStream input, byte[] b) {
  this.fileRealPath=fileRealPath;
  this.fileNameLong=fileNameLong;
  this.input=input;
  this.b=b;
 }public String getFileRealPath() {
  return fileRealPath;
 }public void setFileRealPath(String fileRealPath) {
  this.fileRealPath = fileRealPath;
 } public String getReturnStr() {
  return returnStr;
 } public void setReturnStr(String returnStr) {
  this.returnStr = returnStr;
 }public String getFileNameLong() {
  return fileNameLong;
 }public void setFileNameLong(String fileNameLong) {
  this.fileNameLong = fileNameLong;
 }
 public InputStream getInput() {
  return input;
 }public void setInput(InputStream input) {
  this.input = input;
 } public byte[] getB() {
  return b;
 }public void setB(byte[] b) {
  this.b = b;
 } public synchronized  void run() {
  // 获取上传的文件名称
  // String fileNameLong = uploadFile.getOriginalFilename();
   // 获取文件扩展名
   String extensionName = fileNameLong.substring(fileNameLong .lastIndexOf(".") + 1);
   if (!extensionName.equals("jpg")) {
    if (!extensionName.equals("gif")) {
     if (!extensionName.equals("png")) {
      this.returnStr="false";  }} }
   String baseDir = "/goods/";
   String fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
   /* 文件存储的相对路径 */
   String saveDirPath = baseDir + fileFolder + "/";
   /* 文件存储在容器中的绝对路径 */
   // String saveFilePath
   String saveFilePath = fileRealPath + saveDirPath;
   /*System.out.println(saveFilePath);*/
   /* 构建文件目录以及目录文件 */
   File fileDir = new File(saveFilePath);if (!fileDir.exists()) { fileDir.mkdirs();}
   /* 重命名文件 */
   String filename = Digest.dateFormatString(new Date()).replaceAll(" ", "").replaceAll(":", "");
   try {
    FileOutputStream out = new FileOutputStream(saveFilePath + filename
      + "." + extensionName);
    out.write(b); // 写入文件
    out.close();
    BufferedImage p_w_picpath = ImageIO.read(input);
    ImageIO.write(ResizeImage.resizeImage(p_w_picpath, 100, 100), "jpg",
      new File(saveFilePath + filename + "_small." + extensionName));
   } catch (Exception e) { e.printStackTrace(); }returnStr=saveDirPath + filename + "_small." + extensionName; }}