multipart/form-data多文件上传

4 篇文章 0 订阅
1 篇文章 0 订阅

1.html

anction为后端路径 
enctype="multipart/form-data"为文件提交类型

 <form action="/AppStore/file/upload" name="myForm" id="fileForm"  enctype="multipart/form-data" method="post" class="form-horizontal">
                <!-- START panel-->
                <div class="panel panel-default">

                    <input type="text" name="id" value="{{id}}" hidden>
                    <div class="panel-heading">
                        <div class="panel-title">上传文件</div>
                    </div>
                    <div class="panel-body">
                        <fieldset>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">安卓安装包</label>
                                <div class="col-sm-6">
                                    <input type="file" accept=".apk" name="apkFile" required="required" />
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-2 control-label">苹果安装包</label>
                                <div class="col-sm-6">
                                    <input type="file" accept=".ipa" name="ipaFile" required="required" />
                                </div>
                            </div>
                        </fieldset>
                        <fieldset>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">上传图标</label>
                                <div class="col-sm-6">
                                    <input type="file" accept=".png" name="appIcon" required="required"/>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset>
                            <div class="row">
                                <label class="col-sm-2 control-label">上传图片</label>

                                <div style="margin-left:300px;margin-top:20px">
                                    演示图片1
                                    <input type="file" accept=".png" name="appShow" required="required"/><br/>
                                </div>
                                <div style="margin-left:300px;margin-top:20px">
                                    演示图片2
                                    <input type="file" accept=".png" name="appShow"   required="required"/><br/>
                                </div>
                                <div style="margin-left:300px;margin-top:20px">
                                    演示图片3
                                    <input type="file" accept=".png" name="appShow" required="required"/><br/>
                                </div>
                                <div style="margin-left:300px;margin-top:20px">
                                    演示图片4
                                    <input type="file" accept=".png" name="appShow"  required="required"/><br/>
                                </div>
                            </div>
                        </fieldset>
                    </div>
                    <div class="panel-footer text-center">
                        <button type="button" class="btn btn-info" ng-click="saveReport()"  ng-disabled="myForm.$invalid">确认</button>
                    </div>

                </div>
                <!-- END panel-->
            </form>

2.springmvc后端

multipartResolver 根据文件名解析获取文件

@RequestMapping(value="/upload", method=RequestMethod.POST	)
	@ResponseBody
	public Map<String, Object> upload(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> resMap = new HashMap<String, Object>();
//		获取appId
		int id = Integer.parseInt(request.getParameter("id"));
		resMap.put("id", id);
		String rootPath=UploadFileController.class.getResource("/").getFile();
		rootPath = rootPath.substring(1, rootPath.length()-8);
		String apkPath=rootPath+"file"+"/apk/";
		String ipaPath=rootPath+"file"+"/ipa/";
		String appIconPath=rootPath+"img"+"/AppIcon"+"/";
		String appShowPath=rootPath+"img"+"/AppShow"+"/"+id+"/";
		try {


		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//判断 request 是否有文件上传,即多部分请求
		System.out.println("1");
		if(multipartResolver.isMultipart(request)){
			System.out.println("2");
			//转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
			MultipartFile apkFile=multiRequest.getFile("apkFile");
			MultipartFile ipaFile=multiRequest.getFile("ipaFile");
			MultipartFile appIconFile=multiRequest.getFile("appIcon");
			List<MultipartFile> appShowFiles=multiRequest.getFiles("appShow");

			UploadMultipartFile.saveOneFile(apkFile, apkPath, id);
			UploadMultipartFile.saveOneFile(ipaFile, ipaPath, id);
			UploadMultipartFile.saveOneFile(appIconFile, appIconPath, id);
			UploadMultipartFile.saveListFile(appShowFiles, appShowPath, id);

			Map<String, String> checkMap=fileService.checkFile(id);
			 for (Object o : checkMap.keySet()) {
				 System.out.println("key=" + o + " value=" + checkMap.get(o));
				 if (checkMap.get(o).equals("false")) {
					 resMap.put("result", "error");
					break;
				}else {
					resMap.put("result", "success");
				}
				  }
		}else {
			resMap.put("result", "error");
		}} catch (Exception e) {
			resMap.put("result", "error");
			return resMap;
		}
		return resMap;
	}

3.UploadMultipartFile

将MultipartFile保存为本地文件

package com.baosight.webapp.util;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.baosight.webapp.web.UploadFileController;

public class UploadMultipartFile {
	public static void saveOneFile(MultipartFile file,String path,int id){
		try {


		System.out.println("empty");
		if (!file.isEmpty()) {
			System.out.println("not empty");
			System.out.println("file:"+file.getOriginalFilename());
			String OriginalNameArr[]=file.getOriginalFilename().split("[.]");
			String fileName = id+"."+OriginalNameArr[OriginalNameArr.length-1];
			path=path+fileName;
			System.out.println("path:"+path);
			File localFile = new File(path);
			try {
				if(!localFile.getParentFile().exists()) {
					 //如果目标文件所在的目录不存在,则创建父目录
					 localFile.getParentFile().mkdirs();
					 System.out.println("parent:"+localFile.getParentFile().getPath());
				 }
				file.transferTo(localFile);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		} catch (Exception e) {
			System.out.println("exce[tion2");
			System.out.println(e.getMessage());
		}
	}

	public static void saveListFile(List<MultipartFile> files,String path,int id){
		try {

		String path2="";
		if(files!=null&&files.size()>0){
			int j=0;
			for (MultipartFile multipartFile : files) {
				if (!multipartFile.isEmpty()) {


				 j++;
				 String OriginalNameArr[]=multipartFile.getOriginalFilename().split("[.]");
				 path2=path+j+"."+OriginalNameArr[OriginalNameArr.length-1];
				 File localFile = new File(path2);
				 if(!localFile.getParentFile().exists()) {
					 //如果目标文件所在的目录不存在,则创建父目录
					 localFile.getParentFile().mkdirs();
					 System.out.println("parent:"+localFile.getParentFile().getPath());
				 }
			try {
				multipartFile.transferTo(localFile);
			} catch( Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				}
		}
		}} catch (Exception e) {
			System.out.println("exception1");
			// TODO: handle exception
		}
	}



}
4.阻止表单提交后的跳转动作
引入jquery.js和jquery-form.js文件
本文这里基于angularjs+html5开发,有angularjs多文件上传有问题后,使用form表单上传文件,为了有回调信息使用jquery-form.js阻止表单跳转
按钮触发的事件:ng-click="saveReport()"
 $scope.saveReport=function saveReport() {
        $scope.showFile=false;
        $scope.showProgress=true;
        // jquery 表单提交
        $("#fileForm").ajaxSubmit(function(message) {
            console.log( message);

            if(message.result=="success"){
                alert("上传成功");

                $state.go("dash",null,{reload:true});
            }else{
                alert("上传失败,请在更新中重新上传");
                $state.go("dash");
            }
           
        });

        return false; // 必须返回false,阻止页面跳转
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值