异步上传图片

Posted 咖哇(Java)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步上传图片相关的知识,希望对你有一定的参考价值。

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"/>

  

以上是关于异步上传图片的主要内容,如果未能解决你的问题,请参考以下文章

摒弃FORM表单上传图片,异步批量上传照片

Ajax实现异步上传图片

ajax异步上传图片&SpringMVC后台代码

php+ajax实现异步上传文件或图片功能

thinkphp 使用插件异步上传图片或者文件

Ajax简单异步上传图片并回显