图片附件上传(前后端代码)

 当我们需要上传一个图片或者附件时,我们必须现在前台页面获取得到该图片或者附件,然后通过异步将请求发送到后端java控制层进行业务的逻辑处理,一下就是代码实例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>添加</title>
	<#include "/common/global_css.ftl">
	<link href="${request.getContextPath()}/css/validform/style.css" rel="stylesheet" type="text/css" media="all"/>
	<link href="${request.getContextPath()}/css/chosen/chosen.css" rel="stylesheet" type="text/css"/>
	<link href="${request.getContextPath()}/css/jbox/jbox_blue.css" rel="stylesheet" type="text/css" id="jbox"/>
	<style type="text/css">
		body{margin:0px;font-size:12px;color:#999;}
		.form{overflow:auto;background:#F7F7F7;height:100%;}
	</style>
</head>
<body>
	<div class="form">
		<form class="addForm" target="_parent" id="courseAddForm" action="${request.getContextPath()}/course/course/saveCourse" method="post">
			<input type="hidden" id="pageContext" value="${request.getContextPath()}" />
			<input type="hidden" id="partnerId" name="partnerId" value="${Session.partnerId}" />
			<table border="0" cellspacing="0" cellpadding="0" width="100%" style="margin-top:20px;" class="boxTable boxmar">
			<#--  ${request.getContextPath()}/images/receive.png 初始化展示图片的样式,可以为空  -->
		            <tr>
		            	<td align="right" style="width:80px"></td>
		      			<td style="width:150px">
							 <img id="imagePathSrc1" src="${request.getContextPath()}/images/receive.png" width="180" height="150">		      				
		            	</td>
		            	<td>
	    					<div class="Validform_checktip"></div>
	    				</td>
		            </tr>
		            <tr>
		            	<td align="right" style="width:80px"><span class="check">*</span>课程图:</td>
		      			<td style="width:150px">
		      				<input type="hidden" name="courseImage" id="courseImage" class="cword" value="" />
		      				<input type="file" id="photo1">
							<input type="button"  value="上传" onclick="uploadPhotos(1)" class="btn" >
		            	</td>
		            	<td>
	    					<div class="Validform_checktip"></div>
	    				</td>
		            </tr>
		            <tr>
		            	<td align="right" style="width:80px"></td>
		      			<td style="width:150px">
							 <img id="imagePathSrc2" src="${request.getContextPath()}/images/receive.png" width="180" height="150">		      				
		            	</td>
		            	<td>
	    					<div class="Validform_checktip"></div>
	    				</td>
		            </tr>
		            <tr>
		            	<td align="right" style="width:80px"><span class="check">*</span>分享图:</td>
		      			<td style="width:150px">
		      				<input type="hidden" name="courseShareImage" id="courseShareImage" class="cword" value=""/>
		      				<input type="file" id="photo2">
							<input type="button" value="上传" onclick="uploadPhotos(2)" class="btn" >
		            	</td>
		            	<td>
	    					<div class="Validform_checktip"></div>
	    				</td>
		            </tr>
		            <tr>
		            	<td align="right" style="width:80px">课程附件:</td>
		      			<td style="width:150px">
		      				<input type="file" id="file_single"/>
		      				<input type="button"  value="上传" onclick="uploadFiles()" class="btn" >
		      			</td>
		            	<td>
	    					<div class="Validform_checktip"></div>
	    				</td>
		            </tr>
		            <tr>
		            	<td colspan="3" style="padding: 0px 80px;">
	    					<ul id="attachmentLi">
    						</ul>
	    				</td>
		            </tr>
	            <tr align="center">
    				<td colspan="3">
    					<input class="btn" type="button" id="saveBtn" value="保存">
    					<input type="button" class="btn dis cancel" id="cancelBtn" value="取消">
    				</td>
  				</tr>
	  		</table>
		</form>
	</div>
	<script type="text/javascript" src="${request.getContextPath()}/js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/allPage.js" contextPath="${request.getContextPath()}"  id="allPageJs"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/jbox/jquery.jBox.src.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/jbox/jquery.jBox-zh-CN.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/validform/Validform_v5.3.2.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/chosen/chosen.jquery.min.js"></script>
	<script type="text/javascript">
		$(function(){
			$('#courseAddForm').Validform({
				btnSubmit:"#saveBtn", 
				tiptype:2,
				showAllError:true,
				beforeCheck:function(curform){
					//在验证成功后,表单提交前执行的函数,curform参数是当前表单对象。
					//这里明确return false的话表单将不会提交; 
					var courseType = $("input[name='courseType']:checked").val();
					var videoId = $("#videoId option:selected") .val();
				}
			});
			$('.chosen').chosen({
				"no_results_text":'未找到匹配数据!',
				"width":"120px",
				"allow_single_deselect":true
			});
			$('#cancelBtn').click(function(){
				parent.jBox.close(true);
			});
			$(".exist").css("display","none");
		});	
	 //图片上传
	 function uploadPhotos(type){
         //创建上传数据 
	     var myFormData = new FormData();
	     myFormData.append('photos',$('#photo'+type)[0].files[0]);
	     console.log($('#photo'+type)[0].files[0]);
	     var index= $('#photo'+type)[0].files[0].name.lastIndexOf(".");
		 //获取后缀
		 var ext = $('#photo'+type)[0].files[0].name.substr(index+1);
		 //图片上传仅支持JPG和PNG格式的图片
	     if(ext.toUpperCase()=='JPG'||ext.toUpperCase()=="PNG"){
		//图片的上传路径
	     var targetUrl = '${request.getContextPath()}/uploadfile/savephoto';
			$.ajax({
	            type:"post",
	            url:targetUrl,
	            data:myFormData,
	            cache: false,
	            async:false,
	            processData: false,
                contentType: false,
	            success:function(data) {
		    		var result = data;
		    		if(type==1){
			    		$("#imagePathSrc1").attr('src',data);
			    		$("#courseImage").val(data);
		    		}else if(type==2){
		    			$("#imagePathSrc2").attr('src',data);
		    		 	$("#courseShareImage").val(data);
		    		}
		    	}
		    });
		  }else{
	     	jBox.tip('请选择jpg文件或者png文件!');
			return false;
	     }
	 }
	 //上传附件
	 var i=$("#attachmentLi li").length;
	 function uploadFiles(){ 
		 if(i<10){
             //创建上传数据 
		 	 var myFormData = new FormData();
		     myFormData.append('file_single',$('#file_single')[0].files[0]);
			 //文件上传的路径
		     var targetUrl = '${request.getContextPath()}/uploadfile/uploadSingleFile';
			 $.ajax({
		           type:"post",
		           url:targetUrl,
		           data:myFormData,
		           cache: false,
		           async:false,
		           processData: false,
		           contentType: false,
		           success:function(data) {
		           		console.log(data);
		           		if(data!="false"){
				    		var result = data;
				    		var filename=$('#file_single')[0].files[0].name;
				    		var inp='<input type="hidden" name="attachmentSource['+i+'].showname" value="'+filename+'"/>';
				    		    inp+='<input type="hidden" name="attachmentSource['+i+'].href" value="'+result+'"/>';
				    		var li="<li><span>"+filename+"</span>"+inp+"</li>";
				    		$("#attachmentLi").append(li);
				    		i++;
		           		}else{
		           			jBox.tip('上传失败!');
							return false;
		           		}
			    	}
			  });
		 }else{
		 	jBox.tip('上传多个附件不可超过10个!');
			return false;
		 }
	 }
	</script>
</body>
</html>

当数据请求到Java后端时

package com.nuocai.modules.uploadfile.controller;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.nuocai.core.common.utils.upload.FileUploadConstants;
import com.nuocai.core.mybase.Constants;
//这是请求到的具体映射路径
@Controller
@RequestMapping("/uploadfile")
public class UploadController {

	@SuppressWarnings("unused")
	@RequestMapping(value = { "/savephoto" }, method = RequestMethod.POST)
	@ResponseBody
	public String addDish(@RequestParam("photos") MultipartFile file, HttpServletRequest request) throws Exception {
		String savePath = getSavePath("FILE_PATH_IMAGE");
		String path = savePath;// 文件路径
		double fileSize = file.getSize();
		byte[] sizebyte = file.getBytes();
		if (file != null) {// 判断上传的文件是否为空
			String type = null;// 文件类型
			String fileName = file.getOriginalFilename();// 文件原名称
			fileName = reFileNameByUUID(savePath, fileName);
			// 判断文件类型
			type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
			if (type != null) {// 判断文件类型是否为空
				if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
					// 项目在容器中实际发布运行的根路径
					String realPath = request.getSession().getServletContext().getRealPath("/");
					// 自定义的文件名称
					String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
					// 设置存放图片文件的路径
					path = savePath + fileName;
					// 转存文件到指定的路径
					file.transferTo(new File(path));
                    //返回存放该图片的具体位置加上图片命
					return Constants.SAVE_FILE_IMAGE + fileName;
				}
			} else {
				return "false";
			}
		} else {
			return "false";
		}
		return "false";
	}
	@SuppressWarnings("unused")
	@RequestMapping(value = { "/uploadSingleFile" }, method = RequestMethod.POST)
	@ResponseBody
	public String uploadSingleFile(@RequestParam("file_single") MultipartFile file, HttpServletRequest request) throws Exception {
		String savePath = getSavePath("FILE_PATH_FILE");
		String path = savePath;// 文件路径
		double fileSize = file.getSize();
		byte[] sizebyte = file.getBytes();
		if (file != null) {// 判断上传的文件是否为空
			String type = null;// 文件类型
			String fileName = file.getOriginalFilename();// 文件原名称
			fileName = reFileNameByUUID(savePath, fileName);
			// 判断文件类型
			type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
			if (type != null) {// 判断文件类型是否为空
				if ("DOC".equals(type.toUpperCase())||"DOCX".equals(type.toUpperCase())||"XLS".equals(type.toUpperCase())||"XLSX".equals(type.toUpperCase())||"PPT".equals(type.toUpperCase())||"PPTX".equals(type.toUpperCase())||"PDF".equals(type.toUpperCase())) {
					// 项目在容器中实际发布运行的根路径
					String realPath = request.getSession().getServletContext().getRealPath("/");
					// 自定义的文件名称
					String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
					// 设置存放图片文件的路径
					path = savePath + fileName;
					// 转存文件到指定的路径
					file.transferTo(new File(path));
                    //返回存放该附件的具体位置加上图片命
					return Constants.SAVE_FILE_FILES + fileName;
				}
			} else {
				return "false";
			}
		} else {
			return "false";
		}
		return "false";
	}
	private static String getSavePath(String proVal) {

		if (proVal != null && proVal.equals("")) {
			proVal = "";
		}
        //获取该文件存放的具体路径
		String saveFilePath = FileUploadConstants.getPropValue(proVal);
		if (saveFilePath == null || saveFilePath.equals("")) {
			return null;
		}
		if (!saveFilePath.endsWith("/"))
			saveFilePath += "/";
		// 生成文件保存路径
		File aSaveFile = new File(saveFilePath);
		if (!aSaveFile.isDirectory())
			aSaveFile.mkdirs();
		return saveFilePath;
	}
	/**
	 * UUID命名
	 * 
	 */
	public static String reFileNameByUUID(String filePath, String fileName) {
		String uFileName = UUID.randomUUID().toString();
		uFileName = uFileName.substring(0, 8) + uFileName.substring(9, 13) + uFileName.substring(14, 18) + uFileName.substring(19, 23) + uFileName.substring(24);
		int p = fileName.lastIndexOf(".");
		fileName = uFileName + fileName.substring(p, fileName.length());
		File file = new File(filePath + fileName);
		if (file.exists()) {
			fileName = reFileNameByUUID(filePath, fileName);
		}
		return fileName;
	}

}
//这是处理业务逻辑的具体工具类
package com.nuocai.core.common.utils.upload;
import java.io.InputStream;
import java.util.Properties;

public class FileUploadConstants {
	public static String EXCELPATH_USER = "";
	
	private static Properties prop=null;
	
	static{
        //如果执行在Window操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
		String path="/config/fileUploadSavePath_windows.properties";
		if(isLinux()){
            //如果执行在Liunx操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
			path="/config/fileUploadSavePath_linux.properties";
		}
        //获取到输入流
		InputStream in=FileUploadConstants.class.getResourceAsStream(path);
        //如果存在该路径且流不为空,则读取配置文件
		if(in!=null){
			prop=new Properties();
			try {
				prop.load(in);
				EXCELPATH_USER=prop.getProperty("EXCELPATH_USER");
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	public static String getPropValue(String key){
        //如果执行在Window操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
		String path="/config/fileupload/fileUploadSavePath_windows.properties";
		String val = null;
		if(isLinux()){
                //如果执行在Liunx操作系统中,则找到对应的配置文件所配置的具体文件的存放位置
			path="/config/fileupload/fileUploadSavePath_linux.properties";
		}
        //获取到输入流
		InputStream in=FileUploadConstants.class.getResourceAsStream(path);
        //如果存在该路径且流不为空,则读取配置文件
		if(in!=null){
			prop=new Properties();
			try {
				prop.load(in);
				val = prop.getProperty(key);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return val;
	}
	//判断该代码程序是否执行在Linux操作系统当中
	public  static boolean isLinux(){
		String osType = System.getProperties().getProperty("os.name").toLowerCase();
		if(osType.startsWith("windows")){
			return false;
		}
		else{
			return true;
		}
	}
}
//Window配置文件所在位置 /config/fileupload/fileUploadSavePath_windows.properties 及其内容
FILE_PATH_JS=/web/project/js_css_static/js
FILE_PATH_CSS=/web/project/js_css_static/css
FILE_PATH_IMAGE=/web/project/js_css_static/image/
FILE_PATH_ATTACHMENT=/home/project/upload/attachment
FILE_PATH_IMAGERNAME=/home/project/upload/image
FILE_PATH_FTL=/web/template
FILE_PATH_COURSEITEM=/web/importcourseitem/
FILE_PATH_EXCEL=/home/project/upload/excel
PATH_ASK_CONTENT=/web/project/js_css_static/contentImage
//Linux配置文件所在位置 /config/fileupload/fileUploadSavePath_linux.properties 及其内容
FILE_PATH_JS=e:/nuocai/js
FILE_PATH_CSS=e:/nuocai/css
FILE_PATH_IMAGE=c:/web/project/js_css_static/image/
FILE_PATH_ATTACHMENT=e:/upload/attachment
FILE_PATH_FTL=e\:/userBaseInfo
FILE_PATH_IMAGERNAME=c\:/upload/image
FILE_PATH_COURSEITEM=c\:/fileupload/importcourseitem/
FILE_PATH_EXCEL=c\:/upload/excel
PATH_ASK_CONTENT=c\:/web/project/js_css_static/contentImage
PATH_ASK_CONTENT=c\:/web/project/js_css_static/contentImage
PATH_WX_APP_image=images/WXImage
//常量类所在位置
package com.nuocai.core.mybase;

import com.nuocai.core.common.utils.upload.FileUploadConstants;
import com.nuocai.core.myutil.PropertiesLoader;


/**
 * 全局常量
 * 
 * @author zj
 * 
 */
public abstract class Constants {
	/**
     * 文件存储路径
     */
    public static final String SAVE_FILE_JS="http://static.gswldx.com/js/";
    public static final String SAVE_FILE_CSS="http://static.gswldx.com/css/";
    public static final String SAVE_FILE_IMAGE="http://static.gswldx.com/image/";
    public static final String SAVE_FILE_EXCEL="http://static.gswldx.com/upload/excel/";
    public static final String SAVE_FILE_FILES="http://static.gswldx.com/file/";
}

最后就是配置相关的nginx动静分离服务器

名字:static.gswldx.com.conf

server {
	listen       80;
	server_name  static.gswldx.com;
	access_log  static.yijian119.com.access.log;
	location / {		
		#location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ {
        	#        valid_referers *.wafutech.com;
                #	if ($invalid_referer) {
                #        	return 403;
                #	}
        	#}

		root   C:/web/project/js_css_static/;
		#index  index.html index.htm;
	}

}

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值