1. 程式人生 > >spring+mybatis+ajax上傳下載檔案

spring+mybatis+ajax上傳下載檔案

前端程式碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
/* $(function(){
	$("#upexcel").click(upExcel);
}) */

function upFiles() {
    var formData = new FormData($( "#uploadForm" )[0]);
     $.ajax({
         url: '/files/upFiles.do',
         type: 'POST',
         data: formData,
         async: false,
         cache: false,
         contentType: false,
         processData: false,
         //dataType:'json',
         success: function (returndata) {
             alert(returndata.msg);
         },
         error: function (returndata) {
             alert(returndata);
         }
    });
}

function addFiles(){
	var formData = new FormData();
	for(var i=0; i<$('#file')[0].files.length;i++){
	    formData.append('files', $('#file')[0].files[i]);
	}
	$.ajax({
	   url: "/files/addFiles.do",
	   type: "POST",
	   processData: false,
	   contentType: false,
	   data: formData,
	   success: function (returndata) {
	       alert(returndata.msg);
	   },
	   error: function (returndata) {
	       alert(returndata);
	   }
	});
}

</script>
</head>
<body>

	<form id= "uploadForm">
      <!-- <p >指定檔名: <input type="text" name="fileName" value= ""/></p > -->
      <p >上傳單個檔案: <input type="file" name="file"/>
      <input type="button"  value="上傳" onclick="upFiles()" /></p>
	</form>

	<form enctype="multipart/form-data">    
     <p >上傳多個檔案:<input  type="file" multiple="multiple" id="file" name="files" >
     <input  type="button" id="btn" value="提交" onclick="addFiles()" /></p>
    </form>

<p><a href="/files/downFiles.do">伺服器下載</a></p>
<p><a href="/files/getFiles.do">資料庫下載</a></p>

</body>
</html>
controller
package com.web.controller.files;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.entity.files.Files;
import com.service.files.FilesService;
import com.util.IdUtil;
import com.util.Result;

@Controller
@RequestMapping("/files/*")
public class FilesController {
	
	@Resource
	private FilesService filesService;
	
	/**
	 * 一次上傳單個檔案到伺服器和資料庫
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping("upFiles.do")
	@ResponseBody
	public Result upFiles(HttpServletRequest request) throws IllegalStateException, IOException{
		//String fileName=request.getParameter("fileName");
		// 轉型為MultipartHttpRequest:   
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
        // 獲得檔案:
        MultipartFile file = multipartRequest.getFile("file");
		//獲取檔案引數
		String files_id=IdUtil.createId();
		String files_origin_name=file.getOriginalFilename();//檔案原始名字
		System.out.println("file_name:"+file.getOriginalFilename());
		String files_type=file.getContentType();//檔案型別
		String files_server_path="files/"+System.currentTimeMillis()+
				files_origin_name.substring(files_origin_name.indexOf("."));//伺服器路徑
		byte[] files_content=file.getBytes();//最大2147483647位元組
		//存到伺服器上
		//String realPath = request.getSession().getServletContext().getRealPath("/files");//servlet下的路徑
		//String files_server_path=realPath+System.currentTimeMillis()+files_origin_name.substring(files_origin_name.indexOf("."));
		if(file!=null){
			File filepath=new File(files_server_path);
			if(!filepath.exists()){//判斷改路徑是否存在
				filepath.mkdirs();
			}
			file.transferTo(new File(files_server_path));
		}
		Files files=new Files();
		files.setFiles_id(files_id);
		files.setFiles_origin_name(files_origin_name);
		files.setFiles_type(files_type);
		files.setFiles_server_path(files_server_path);
		files.setFiles_content(files_content);
/*		在向mysql資料庫儲存影象檔案大於1048576時丟擲com.mysql.jdbc.PacketTooBigException: 異常
		  以下是解決方案:
		  我用的MySQL版本是5.0
		  在mysql安裝目錄下找到my.ini檔案,在最後加入一行:
		max_allowed_packet = 10M(該值根據需要設定)
		用dos視窗中使用net stop mysql命令關閉mysql然後重啟net start mysql
		重新插入影象(不超過10M),發現問題已經解決了!*/
		Result result=filesService.addFiles(files);
		return result;
	}
	
/*	@RequestMapping("addFiles.do")
	@ResponseBody
	public Result addFiles(HttpServletRequest request) throws Exception {
		// 將當前上下文初始化給 CommonsMutipartResolver (多部分解析器)
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		// 檢查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 將request變成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 獲取multiRequest 中所有的檔名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 一次遍歷所有檔案
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				System.out.println("file.getOriginalFilename():"+file.getOriginalFilename());
				
				if (file != null) {
					String path = "addfiles/" + file.getOriginalFilename();
					File filepath=new File(path);
					if(!filepath.exists()){//判斷改路徑是否存在
						filepath.mkdirs();
					}
					// 上傳
					file.transferTo(new File(path));
				}
			}
		}
		Result result =new Result();
		result.setMsg("成功");
		return result;
	}*/
	
	/**
	 * 一次性上傳多個檔案
	 * @param request
	 * @param files
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("addFiles.do")
	@ResponseBody
	public Result addFiles(HttpServletRequest request,MultipartFile[] files) throws Exception {
		// 判斷file陣列不能為空並且長度大於0
		if (files != null && files.length > 0) {
			// 迴圈獲取file陣列中得檔案
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 儲存檔案
				// 判斷檔案是否為空
				if (!file.isEmpty()) {
					// 檔案儲存路徑
					String filePath = "addfiles/" + file.getOriginalFilename();
					// 轉存檔案
					file.transferTo(new File(filePath));
				}
			}
		}
		Result result = new Result();
		result.setMsg("成功");
		return result;
	}
	/**
	 * 從伺服器下載檔案
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("downFiles.do")
	public String downFiles(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Files files=filesService.getFiles();
		request.setCharacterEncoding("UTF-8");
		response.setContentType(files.getFiles_type()+";charset=UTF-8");
		//response.addHeader("Content-Disposition","attachment; filename="+files.getFiles_origin_name());
		response.setHeader("Content-Disposition","attachment; filename="+new String(files.getFiles_origin_name() .getBytes("utf-8"),"iso-8859-1"));//設定檔名字
		System.out.println(files.getFiles_origin_name());
		FileInputStream fis=new FileInputStream(files.getFiles_server_path());//讀取檔案
		OutputStream os=response.getOutputStream();//建立輸出流
		byte[] bt=new byte[1024];
		while(fis.read(bt)!=-1){
			os.write(bt);
		}
		fis.close();
		os.flush();
		os.close();
		return null;
	}
	
	/**
	 * 從資料庫下載檔案
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("getFiles.do")
	public void getFiles(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Files files=filesService.getFiles();
		request.setCharacterEncoding("UTF-8");
		response.setContentType(files.getFiles_type()+";charset=UTF-8");
		//response.addHeader("Content-Disposition","attachment; filename="+files.getFiles_origin_name());
		response.setHeader("Content-Disposition","attachment; filename="+new String(files.getFiles_origin_name() .getBytes("utf-8"),"iso-8859-1"));//設定檔名字
		System.out.println(files.getFiles_origin_name());
		FileInputStream fis=new FileInputStream(files.getFiles_server_path());//讀取檔案
		OutputStream os=response.getOutputStream();//建立輸出流
		byte[] bt=files.getFiles_content();
		os.write(bt);
		fis.close();
		os.flush();
		os.close();
	}
	
	
}

service層

package com.service.files;

import com.entity.files.Files;
import com.util.Result;

public interface FilesService {

	public Result addFiles(Files files);
	public Files getFiles();
	
}
service實現層
package com.service.files;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dao.files.FilesDao;
import com.entity.files.Files;
import com.util.Result;

@Service
public class FilesServiceImpl implements FilesService {

	@Resource
	private FilesDao filesDao;
	
	public Result addFiles(Files files) {
		int addRecorder=filesDao.addFiles(files);
		Result result=new Result();
		if(addRecorder!=1){
			result.setStatus(0);
			result.setMsg("上傳資料庫失敗");
		}else{
			result.setStatus(1);
			result.setMsg("上傳資料庫成功");
		}
		return result;
	}

	public Files getFiles(){
		Files files=filesDao.getFiles();
		return files;
	}
	
}
實體類
package com.entity.files;

import java.util.Arrays;

import com.entity.base.BaseEntity;

public class Files extends BaseEntity {

	private String files_id;
	private String files_origin_name;
	private String files_server_path;
	private String files_type;
	private byte[] files_content;
	public String getFiles_id() {
		return files_id;
	}
	public void setFiles_id(String files_id) {
		this.files_id = files_id;
	}
	public String getFiles_origin_name() {
		return files_origin_name;
	}
	public void setFiles_origin_name(String files_origin_name) {
		this.files_origin_name = files_origin_name;
	}
	public String getFiles_server_path() {
		return files_server_path;
	}
	public void setFiles_server_path(String files_server_path) {
		this.files_server_path = files_server_path;
	}
	public String getFiles_type() {
		return files_type;
	}
	public void setFiles_type(String files_type) {
		this.files_type = files_type;
	}
	public byte[] getFiles_content() {
		return files_content;
	}
	public void setFiles_content(byte[] files_content) {
		this.files_content = files_content;
	}
	@Override
	public String toString() {
		return "Files [files_id=" + files_id + ", files_origin_name=" + files_origin_name + ", files_server_path="
				+ files_server_path + ", files_type=" + files_type + ", files_content=" + Arrays.toString(files_content)
				+ "]";
	}
	
	
}
dao層
package com.dao.files;

import com.entity.files.Files;

public interface FilesDao {
	
	public int addFiles(Files files);
	public Files getFiles();

}
sql語句
<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
  <mapper namespace="com.dao.files.FilesDao">
  
<!-- 傳參規則:增加資料記錄傳實體類,查詢和修改較少引數時用map -->

	<!-- 開始:根據傳入的條件向files表中插入資料 -->
	<insert id="addFiles" parameterType="com.entity.files.Files" >
	insert into files(files_id,files_origin_name, files_type, files_server_path,files_content) 
	values(#{files_id},#{files_origin_name},#{files_type},#{files_server_path},#{files_content})
	</insert>
	<!-- 開始:根據傳入的條件向files表中插入資料 -->
	
   <!-- 開始:根據傳入的條件查詢files表中的資料 -->
   <select id="getFiles" resultType="com.entity.files.Files">
   	SELECT * FROM files LIMIT 0,1
   </select>
   <!-- 結束:根據傳入的條件查詢files表中的資料 -->
  	
</mapper> 

配置springmvc

    <!-- 圖片獲取 maxUploadSize:設定最大限制 位元組為單位-->  
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <property name="maxUploadSize" value="4294967296"></property>  
	</bean>

資料庫結構