1. 程式人生 > >異步上傳圖片

異步上傳圖片

sof file標簽 ast war struts2 cli return save ....

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"
	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>01_圖片異步上傳</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<!-- 前端控制器 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

  

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.devMode" value="true"></constant>

	<package name="normal-demo" namespace="/" extends="struts-default">
		<action name="*" method="do_{1}" class="com.itheima.upload.CustomerAction">

		</action>
	</package>
</struts>

  

CustomerAction.java

package com.itheima.upload;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.itheima.crm.utils.UploadUtils;

import com.opensymphony.xwork2.ActionSupport;


public class CustomerAction extends ActionSupport  {
	private static final long serialVersionUID = -3281746108664320233L;

	// 圖片上傳
	private File image_upload;// 上傳後的文件
	private String image_uploadContentType;// 類型
	private String image_uploadFileName;// 上傳的文件名稱

	// 讀取配置中的properties
	private String uploadDir ="F:/crm/images";


	public File getImage_upload() {
		return this.image_upload;
	}


	public void setImage_upload(File image_upload) {
		this.image_upload = image_upload;
	}


	public String getImage_uploadContentType() {
		return this.image_uploadContentType;
	}


	public void setImage_uploadContentType(String image_uploadContentType) {
		this.image_uploadContentType = image_uploadContentType;
	}


	public String getImage_uploadFileName() {
		return this.image_uploadFileName;
	}


	public void setImage_uploadFileName(String image_uploadFileName) {
		this.image_uploadFileName = image_uploadFileName;
	}


	public String do_saveImage() {

		System.out.println("contentType : " + image_uploadContentType);
		System.out.println("fileName : " + image_uploadFileName);

		try {

			String stuffix = image_uploadFileName.substring(image_uploadFileName.lastIndexOf("."));

			// 文件名稱命名
			String path = UploadUtils.getPath(image_upload).concat(stuffix);

			File file = new File(uploadDir + path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}

			FileUtils.copyFile(image_upload, file);

			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write("{‘path‘:‘"+path+"‘}");  // 返回json , 圖片路徑信息
		} catch (IOException e) {
			return NONE;
		}

		return NONE;
	}
	
}

  

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<!--4.JQuery類庫-->
<script src="js/jquery-1.11.3.js" type="text/javascript" charset="utf-8"></script>
<script src="js/ajaxfileupload.js" type="text/javascript" charset="utf-8"></script>


<script type="text/javascript">
	$(function() {
		/*============== 異步上傳文件 start ========================*/
		$(‘#btn_submit‘).on(‘click‘, function() {
			var fileName = $("#upload").val();
			if (fileName == "") {
				console.log("=== 沒有選擇文件 ====")
				return;
			}
			//alert("fileName = "+fileName);
			$.ajaxFileUpload({
				url : ‘${pageContext.request.contextPath }/customer/saveImage‘,
				secureuri : false,
				fileElementId : ‘image_upload‘,//file標簽的id  
				type : ‘post‘,
				dataType : ‘json‘, //返回值類型 一般設置為json  
				success : function(data, status) //服務器成功響應處理函數  
				{
				    console.log(data);
				    var src = "${pageContext.request.contextPath }/images"+data.path;
					$("#img").attr("src",src);
				},
				error : function(data, status, e)//服務器響應失敗處理函數  
				{
					alert("服務器掛了....需要重啟...	");
				}
			});
		});
		/*============== 異步上傳文件 end ========================*/
	});
	
</script>
</head>
<body>

	<table style="margin-top: 10px; margin-left: 10px">
		<tr>
			<td><input type="file" name="image_upload" id="image_upload" /></td>
			<td><input type="button" value="上傳文件" id="btn_submit"></td>
		</tr>
	</table>
	<div id="content" style="height: 100%; width: 100%" align="center">
		<img alt="圖片~~~~" src="" id="img">
	</div>
</body>

  

在tomcat配置文件裏添加虛擬路徑

Context docBase="F:/crm/images" path="/upload/images"/>

  

異步上傳圖片