angular上传文件到服务器

本文详细介绍了如何使用AngularJS进行文件上传操作,包括前端页面设计、控制器与服务层的实现,以及与后端Spring MVC的交互过程。通过具体代码示例,展示了如何利用FormData对象提交文件,以及如何在后端配置MultipartResolver处理文件上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中很多时候都会用到上传文件到服务器,因此在这里实现一下
1.给按钮绑定事件

<button ng-click="uploadFile()" type="button" >
      上传
</button>  

2.创建基础成层

//定义模块
var app = angular.module("pyg", []);

3.创建controller层
3.1创建基础baseController

先空着就行

3.2创建控制controller

//控制层 
app.controller('goodsController' ,function($scope,$controller, uploadService){
	$controller('baseController',{$scope:$scope});//继承
   scope.image = {url:'', color:''};
   $scope.uploadFile = function () {
       uploadService.uploadFile().success(function (res) {
           if(res.success){
               $scope.image.url = res.message;
           } else {
                alert(res.message);
           }
       });
   }
}

4.创建uploadService.js

//服务层
app.service('uploadService',function($http){
          
   this.uploadFile = function () {
      //FormData 就是 XMLHttpRequest Level 2 新增的一个对象,利用它来提交表单、模拟表单提交,当然最大的优势就是可以上传二进制文件
      //	FormData 就是 XMLHttpRequest Level 2 新增的一个对象,利用它来提交表单、模拟表单提交,最大的优势就是可以上传二进制文件
      //	设置’Content-Type’:undefined,浏览器会把Content-Type 设置为 multipart/form-data,并填充当前绑定的数据,如果手动设置为:’Content-Type’:multipart/form-data,后台会抛出异常:the current request boundary parameter is null。 
	//	file.files[0]是document.getElementById('file').files[0]的简写

      var formData = new FormData();
        formData.append('file', file.files[0]);//file.files[0]是document.getElementById('file').files[0]的简写
      return $http({
         method:'post',
         url:'../../file/upload',
         data:formData,//向后台发送的数据
         headers:{'Content-type':undefined},
         transformRequest: angular.identity
      })
    }
});

5.回显数据

<img  src="{{image.url}}" width="200px" height="200px">

6.修改spring-mvc.xml配置文件

<context:property-placeholder location="classpath:config/application.properties"/>
<!-- 配置多媒体解析器 -->
<bean id="multipartResolver"
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <property name="defaultEncoding" value="UTF-8"></property>
   <!-- 设定文件上传的最大值 5MB,5*1024*1024 -->
   <property name="maxUploadSize" value="5242880"></property>
</bean>

5.创建后台UploadController.java

@RestController
@RequestMapping("/file")
public class UploadController {
   @Value("${FILE_SERVER_URL}")
   private String FILE_SERVER_URL;//文件服务器地址

   @RequestMapping("/upload")
   public Result upload( MultipartFile file){
      //1、取文件的扩展名
      String originalFilename = file.getOriginalFilename();
      String extName = originalFilename.substring(originalFilename.lastIndexOf(".")
            + 1);
      try {
         //2、创建一个 FastDFS 的客户端
         FastDFSClient fastDFSClient
               = new FastDFSClient("classpath:config/fdfs_client.conf");
         //3、执行上传处理
         String path = fastDFSClient.uploadFile(file.getBytes(), extName);
         //4、拼接返回的 url 和 ip 地址,拼装成完整的 url
         String url = FILE_SERVER_URL + path;
         return new Result(true,url);
      } catch (Exception e) {
         e.printStackTrace();
         return new Result(false, "上传失败");
      }
   }

}

6.提供application.properties配置文件

FILE_SERVER_URL=http://192.168.25.133/

7.提供fdfs_client.conf配置文件

tracker_server=192.168.25.133:22122

提供工具类FastDFSClient代码如下:

public class FastDFSClient {

	private TrackerClient trackerClient = null;
	private TrackerServer trackerServer = null;
	private StorageServer storageServer = null;
	private StorageClient1 storageClient = null;
	
	public FastDFSClient(String conf) throws Exception {
		if (conf.contains("classpath:")) {
			conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
		}
		ClientGlobal.init(conf);
		trackerClient = new TrackerClient();
		trackerServer = trackerClient.getConnection();
		storageServer = null;
		storageClient = new StorageClient1(trackerServer, storageServer);
	}
	
	/**
	 * 上传文件方法
	 * <p>Title: uploadFile</p>
	 * <p>Description: </p>
	 * @param fileName 文件全路径
	 * @param extName 文件扩展名,不包含(.)
	 * @param metas 文件扩展信息
	 * @return
	 * @throws Exception
	 */
	public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
		String result = storageClient.upload_file1(fileName, extName, metas);
		return result;
	}
	
	public String uploadFile(String fileName) throws Exception {
		return uploadFile(fileName, null, null);
	}
	
	public String uploadFile(String fileName, String extName) throws Exception {
		return uploadFile(fileName, extName, null);
	}
	
	/**
	 * 上传文件方法
	 * <p>Title: uploadFile</p>
	 * <p>Description: </p>
	 * @param fileContent 文件的内容,字节数组
	 * @param extName 文件扩展名
	 * @param metas 文件扩展信息
	 * @return
	 * @throws Exception
	 */
	public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
		
		String result = storageClient.upload_file1(fileContent, extName, metas);
		return result;
	}
	
	public String uploadFile(byte[] fileContent) throws Exception {
		return uploadFile(fileContent, null, null);
	}
	
	public String uploadFile(byte[] fileContent, String extName) throws Exception {
		return uploadFile(fileContent, extName, null);
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值