- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>测试</title>
- <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
- </head>
- <body>
- <input type="file" id="file" onchange="ajaxFileUpload();" />
- </body>
- <script>
- function ajaxFileUpload() {
- var form = new FormData; //创建一个FormData对象
- form.append('file',$("#file").get(0).files[0]); //将文件放到FormData对象中
- console.log(form);
- $.ajax({
- url : "http://127.0.0.1:82/yiwei/upload/imgUpload",//访问路径
- contentType: false,
- processData: false,
- type:"post",
- data :form,
- dataType : "json"
- }).success(function(data,status){
- if(status=="success"){
- if(data.code==200){
- alert("文件上传成功");
- }
- if(data.code==400){
- alert("文件上传失败");
- }
- }
- }).error(function(){
- alert("服务器未响应");
- });
- }
- </script>
- </html>
这里我是用的maven项目,还有就是我的文件是通过ftp上传到我的另一个服务器上的,除去最基本的依赖后,还需要三个依赖
- <span style="white-space:pre;"> </span><dependency>
- <groupId>commons-net</groupId>
- <artifactId>commons-net</artifactId>
- <version>3.1</version>
- </dependency>
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </dependency>
- <!-- commons-io -->
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
springmvc
- package top.yiwei.controller.upload;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.UUID;
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.multipart.MultipartHttpServletRequest;
- import top.yiwei.common.upload.FtpUtil;
- import top.yiwei.common.JsonUtil;
- @RestController
- @RequestMapping("upload")
- /**
- * 上传接口
- * @author Fanqiang
- * @typeNameUploadController
- * @date 2017年6月16日;上午9:56:43
- */
- public class UploadController {
- private static FtpUtil FTPUTIL;
- private static String FTPPSTH = "xxx";
- static{
- System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>创建ftp连接");
- FTPUTIL = new FtpUtil("xxx.xxx.xxx.xxx", xx, "xxxx", "xxxx");
- System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ftp连接成功!");
- if(FTPUTIL.open()){
- System.out.println("---------------------------->ftp服务开启成功!");
- System.out.println("---------------------------->开始生成上传目录...");
- FTPUTIL.mkDir(FTPPSTH);
- System.out.println("---------------------------->生成目录成功");
- }
- }
- /**
- * 头像修改
- * @param req
- * @return
- * @throws IOException
- */
- @RequestMapping("/imgUpload")
- public String fileUpload(HttpServletRequest req) throws IOException {
- MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;
- MultipartFile file = request.getFile("file");
- if(file!=null){
- /** 获取文件的后缀* */
- String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
- /** 使用UUID生成文件名称* */
- String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称
- /** 将文件转化为字节流 **/
- InputStream inputStream = file.getInputStream();
- System.out.println("上传图片"+logImageName);
- FTPUTIL.upload(inputStream,logImageName, FTPPSTH);
- System.out.println("----------------------------->图片上传成功");
- return JsonUtil.success();
- }
- return JsonUtil.error("头像上传失败!!!");
- }
- }
ftpUtil
- package top.yiwei.common.upload;
- import java.io.IOException;
- import java.io.InputStream;
- import org.apache.commons.net.ftp.FTP;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPReply;
- /**
- *
- * @author Fanqiang
- * @typeName FtpUtil
- * @date 2017年6月12日;上午8:02:55
- */
- public class FtpUtil{
- private FTPClient ftpClient = null;
- private String server;
- private int port;
- private String userName;
- private String userPassword;
- public FtpUtil(String server, int port, String userName, String userPassword) {
- this.server = server;
- this.port = port;
- this.userName = userName;
- this.userPassword = userPassword;
- }
- /**
- * 连接服务器
- * @return 连接成功与否 true:成功, false:失败
- */
- public boolean open() {
- if (ftpClient != null && ftpClient.isConnected()) {
- return true;
- }
- try {
- ftpClient = new FTPClient();
- // 连接
- ftpClient.connect(this.server, this.port);
- ftpClient.login(this.userName, this.userPassword);
- setFtpClient(ftpClient);
- // 检测连接是否成功
- int reply = ftpClient.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- this.close();
- System.err.println("FTP server refused connection.");
- System.exit(1);
- }
- System.out.println("open FTP success:" + this.server + ";port:" + this.port + ";name:" + this.userName
- + ";pwd:" + this.userPassword);
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally or ascii
- return true;
- } catch (Exception ex) {
- this.close();
- ex.printStackTrace();
- return false;
- }
- }
- /**
- * 选择上传的目录,没有创建目录
- * @param ftpPath 需要上传、创建的目录
- * @return
- */
- public boolean mkDir(String ftpPath) {
- if (!ftpClient.isConnected()) {
- return false;
- }
- try {
- // 将路径中的斜杠统一
- char[] chars = ftpPath.toCharArray();
- StringBuffer sbStr = new StringBuffer(256);
- for (int i = 0; i < chars.length; i++) {
- if ('\\' == chars[i]) {
- sbStr.append('/');
- } else {
- sbStr.append(chars[i]);
- }
- }
- ftpPath = sbStr.toString();
- System.out.println("ftpPath:" + ftpPath);
- if (ftpPath.indexOf('/') == -1) {
- // 只有一层目录
- ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
- ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
- } else {
- // 多层目录循环创建
- String[] paths = ftpPath.split("/");
- for (int i = 0; i < paths.length; i++) {
- ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
- ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
- }
- }
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * 上传文件到FTP服务器 文件字节流
- * @param fis 上传的文件字节流
- * @param ftpFileName 上传到服务器的文件名
- * @param ftpDirectory 上传到FTP的目录
- * @return
- */
- public boolean upload(InputStream fis, String ftpFileName, String ftpDirectory) {
- if (!ftpClient.isConnected()) {
- return false;
- }
- boolean flag = false;
- if (ftpClient != null) {
- try {
- ftpClient.setBufferSize(100000);
- ftpClient.setControlEncoding("UTF-8");
- // 设置文件类型(二进制)
- ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
- // 上传
- flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "iso-8859-1"), fis);
- } catch (Exception e) {
- this.close();
- e.printStackTrace();
- return false;
- } finally {
- try {
- fis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- System.out.println("上传文件成功,本地文件名: " + ftpFileName + ",上传到目录:" + ftpDirectory + "/" + ftpFileName);
- return flag;
- }
- /**
- * 关闭链接
- */
- public void close() {
- try {
- if (ftpClient != null && ftpClient.isConnected()) {
- ftpClient.disconnect();
- }
- System.out.println("成功关闭连接,服务器ip:" + this.server + ", 端口:" + this.port);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public FTPClient getFtpClient() {
- return ftpClient;
- }
- public void setFtpClient(FTPClient ftpClient) {
- this.ftpClient = ftpClient;
- }
- }
jsonUtil
- package top.yiwei.common;
- import java.util.HashMap;
- import java.util.Map;
- import net.sf.json.JSONObject;
- /**
- * @author
- * @version 1.0
- */
- public abstract class JsonUtil {
- private final static String SUCCESS_CODE = "200";
- private final static String ERROR_CODE = "400";
- private JsonUtil() {
- }
- /**
- * @author
- * @return
- */
- public static String success() {
- Map<String, String> map = new HashMap<String, String>(2);
- map.put("code", SUCCESS_CODE);
- return JSONObject.fromObject(map).toString();
- }
- /**
- * @author
- * @param o
- * @return
- */
- public static String success(Object o) {
- Map<String, Object> map = new HashMap<String, Object>(4);
- map.put("code", SUCCESS_CODE);
- map.put("data", o);
- return JSONObject.fromObject(map).toString();
- }
- /**
- * @author
- * @param msg
- * @return
- */
- public static String error(String msg) {
- Map<String, String> map = new HashMap<String, String>(4);
- map.put("code", ERROR_CODE);
- map.put("msg", msg);
- return JSONObject.fromObject(map).toString();
- }
- }