前端angularJS,服务器fastDSF,后台SSM, 文件上传

 

 

前端逻辑

 

HTML:

<input type="file" id="uploadFile"/>

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

JS:

app.service('uploadService', function ($http) {
 
    this.upload = function () {
        
        var formData = new FormData();
    
        formData.append("file", uploadFile.files[0]);

       return $http({
            url: '../upload/uploadFile.do',
            method: 'post',
            data: formData,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
  
        });
    }
});


app.controller('goodsController', function ($scope, uploadService) {


        $scope.upload= function () {

            uploadService.upload().success(function (response) {

                if (response.success) {
                    alert(response.message);
                } else {
                    alert(response.message);
                }
            });
        }


});

 1. var fileList =  uploadFile.files();这个方法可以得到一个js对象fileList{0:上传的数据,length:1};

     fileList.0 ;就可以得到上传的数据

     fileList[0];js对象获取属性值的另一种写法

    综上可简化为: uploadFile.files[0]    


2.  anjularjs 对于 post 和 get 请求默认的 Content-Type header 是 application/json , 通过设置 ‘Content-Type’: undefined,浏览器会帮我们把 Content-Type 设置为 multipart/form-data,  通过设置 transformRequest: angular.identity ,anjularjs transformRequest function 将序列化表单对象.
            

后台

1.工具类

 

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);
	}
}

 2.controller类

@RestController
@RequestMapping("/upload")
public class uploadController {
    
    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;

    @RequestMapping("/uploadFile")
    public Result uploadFile(MultipartFile file){

        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
            //上传到fastDFS服务器
            String path = fastDFSClient.uploadFile(file.getBytes(), suffix);
            String url = FILE_SERVER_URL+path;
            return new Result(true,url);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"上传失败!");
        }

    }
}

配置文件

1.url.conf

    FILE_SERVER_URL=图片服务器ip

2.springmvc.xml

<!--配置上传的多媒体解析器-->
	<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>

注: 不要忘记把url.conf配置文件引入到springmvc.xml中

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值