【四二学堂】springmvc上传图片通用接口

28 篇文章 0 订阅

这里介绍一下工作中做上传图片的体会,工作中是将选择图片之后异步上传到服务器,返回一个在服务器保存的图片路径,然后赋值到一个隐藏域里,提交表单的时候,再去执行存数据库的操作。

个人感觉这种上传图片的方式要比把表单数据和图片一起提交要好一点。

直接来看代码,这里只展示controller层

import cn.util.DateUtils;
import cn.util.ResponseResult;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Controller层
 * @author Rhine
 *
 */


@Controller
@RequestMapping("api/file/")
public class UploadController {

	/**
	 * 异步上传图片
	 * @param files
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
     * ResponseResult 是自己定义的返回值对象,可随便定义
	 */
	@RequestMapping(value = "upload",method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult uploadFiles(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) throws IllegalStateException, IOException {
		//支持多图片上传
        String result = "";
		for(int i=0;i<files.length;i++){
			if (!files[i].isEmpty()) {

                        //获得原始文件名;
				String fileRealName = files[i].getOriginalFilename();                   


                        //根据图片名称获取一个hash值,算出来的值作为文件路径
				/**********************************************/
				int hashcode = fileRealName.hashCode();//得到hashCode

				int dir1 = hashcode & 0xf; //得到名为1到16的下及文件夹

				int dir2 = (hashcode & 0xf0) >> 4; //得到名为1到16的下下及文件夹

                        //获取服务器指定文件存取路径,我的fileupload在webapp下
				String savedDir = request.getSession().getServletContext().getRealPath("fileupload"); 

				String dir = savedDir + "/" + dir1 + "/" + dir2; //得到文件路径


				/****************************************************/
                        //点号的位置
				int pointIndex =  fileRealName.indexOf(".");     
                        //截取文件后缀                   
				String fileSuffix = fileRealName.substring(pointIndex);             

				String filePreName="";
                        //获取文件名不带后缀名
				filePreName=fileRealName.substring(0,fileRealName.lastIndexOf("."));  

				String date = DateUtils.getDate("yyyyMMddHHmmss");
                
                        //文件存取名
				String savedFileName = filePreName + "_" +date.concat(fileSuffix);       

				File file2 = new File(dir); 	//创建文件夹 如果不存在
				if(!file2.exists()){
					file2.mkdirs();

					System.out.println(dir);
					System.out.println("创建文件夹成功======================"+dir);
				}

				File savedFile = new File(dir,savedFileName );
				boolean isCreateSuccess = savedFile.createNewFile();
				if(isCreateSuccess){
					files[i].transferTo(savedFile);  //转存文件
				}
				String filepath = "/fileupload/" + dir1 + "/" + dir2+ "/" +savedFileName;
				result = result+ filepath + ",";
			}
		}

                //多个文件以逗号分隔,然后去掉最后一个逗号
		result = result.substring(0,result.length()-1);
		return ResponseResult.ok(result);
	}
	
}

前端调用之后,返回一个字符串,多个图片路径以逗号分隔开。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值