图片上传(使用angularJS)

本文详细介绍如何在前端使用FormData对象进行文件上传,包括设置正确的Content-Type、利用MultipartFile在后端接收文件,以及通过FastDFS存储文件并获取URL的过程。

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

前端

  • 表单必须post提交
  • 表单的enctype必须为multipart/form-data
  • 表单中图片输入框type必须为file

后端

  • 必须引入common-fileupload.jar、common-io.jar
  • 必须在springmvc.xml中配置文件解析器
  • 必须在controller方法中使用MultipartFile接收文件
  • 必须生成唯一的文件名

先将要发布的商品图片上传到FastDFS,然后再将图片地址保存到mysql数据库

前端实现

编写service层

//服务层
app.service('uploadService',function($http){
          
   this.uploadFile = function () {
      //FormData 就是 XMLHttpRequest Level 2 新增的一个对象,利用它来提交表单、模拟表单提交,当然最大的优势就是可以上传二进制文件
      var formData = new FormData();
        formData.append('file', file.files[0]);//file.files[0]是document.getElementById('file').files[0]的简写,后台接收时变量名必须是file
      return $http({
         method:'post',
         url:'../../file/upload',
         data:formData,
         headers:{'Content-type':undefined},
         transformRequest: angular.identity
      })
    }
});

注意:
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]的简写,file是文件上传标签的id

后台实现

必须在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>

创建UploadController.java

package com.pinyougou.shop.controller;

import entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import utils.FastDFSClient;

/**
 * controller
 * @author Administrator
 *
 */
@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, "上传失败");
      }
   }

}

注意:
fastDFSClient是一个工具类,封装了fastDFS上传文件步骤

package utils;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

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

将这两项分别配置在配置文件中
访问路径,拼接返回的路径在浏览器可访问:FILE_SERVER_URL=http://192.168.25.133/ 放在一个能被加载到的类中
fastDFS文件上传路径:tracker_server=192.168.25.133:22122 放在config/fdfs_client.conf里面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值