前后台分类跨域上传图片

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="utf-8" />  
  5.         <title>测试</title>  
  6.         <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>  
  7.     </head>  
  8.     <body>  
  9.         <input type="file" id="file" onchange="ajaxFileUpload();" />  
  10.     </body>  
  11.     <script>  
  12.         function ajaxFileUpload() {  
  13.         var form = new FormData;                                           //创建一个FormData对象  
  14.             form.append('file',$("#file").get(0).files[0]);            //将文件放到FormData对象中  
  15.             console.log(form);  
  16.             $.ajax({  
  17.                 url : "http://127.0.0.1:82/yiwei/upload/imgUpload",//访问路径  
  18.                 contentType: false,  
  19.                 processData: false,   
  20.                 type:"post",  
  21.                 data :form,  
  22.                 dataType : "json"  
  23.                   
  24.             }).success(function(data,status){  
  25.                 if(status=="success"){  
  26.                     if(data.code==200){  
  27.                         alert("文件上传成功");  
  28.                     }  
  29.                     if(data.code==400){  
  30.                         alert("文件上传失败");  
  31.                     }  
  32.                 }  
  33.                   
  34.             }).error(function(){  
  35.                 alert("服务器未响应");  
  36.             });  
  37.   
  38.         }  
  39.           
  40.     </script>  
  41. </html>  

这里我是用的maven项目,还有就是我的文件是通过ftp上传到我的另一个服务器上的,除去最基本的依赖后,还需要三个依赖

[html]  view plain  copy
  1. <span style="white-space:pre;">     </span><dependency>  
  2.             <groupId>commons-net</groupId>  
  3.             <artifactId>commons-net</artifactId>  
  4.             <version>3.1</version>  
  5.         </dependency>  
  6.         <dependency>  
  7.             <groupId>commons-fileupload</groupId>  
  8.             <artifactId>commons-fileupload</artifactId>  
  9.             <version>1.3.1</version>  
  10.         </dependency>  
  11.         <!-- commons-io -->  
  12.         <dependency>  
  13.             <groupId>commons-io</groupId>  
  14.             <artifactId>commons-io</artifactId>  
  15.             <version>2.4</version>  
  16.         </dependency>  


springmvc

[java]  view plain  copy
  1. package top.yiwei.controller.upload;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.UUID;  
  6.   
  7. import javax.annotation.Resource;  
  8. import javax.servlet.http.HttpServletRequest;  
  9.   
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RestController;  
  12. import org.springframework.web.multipart.MultipartFile;  
  13. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  14.   
  15. import top.yiwei.common.upload.FtpUtil;  
  16. import top.yiwei.common.JsonUtil;  
  17.   
  18.   
  19. @RestController  
  20. @RequestMapping("upload")  
  21. /** 
  22.  * 上传接口 
  23.  * @author Fanqiang 
  24.  * @typeNameUploadController 
  25.  * @date 2017年6月16日;上午9:56:43 
  26.  */  
  27. public class UploadController {  
  28.       
  29.     private static FtpUtil FTPUTIL;  
  30.     private static String FTPPSTH = "xxx";  
  31.   
  32.     static{  
  33.         System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>创建ftp连接");  
  34.           
  35.         FTPUTIL = new FtpUtil("xxx.xxx.xxx.xxx", xx, "xxxx""xxxx");  
  36.           
  37.         System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ftp连接成功!");  
  38.           
  39.         if(FTPUTIL.open()){  
  40.               
  41.             System.out.println("---------------------------->ftp服务开启成功!");  
  42.             System.out.println("---------------------------->开始生成上传目录...");  
  43.             FTPUTIL.mkDir(FTPPSTH);  
  44.             System.out.println("---------------------------->生成目录成功");  
  45.         }  
  46.     }  
  47.   
  48.     /** 
  49.      * 头像修改 
  50.      * @param req 
  51.      * @return 
  52.      * @throws IOException 
  53.      */  
  54.     @RequestMapping("/imgUpload")  
  55.     public String fileUpload(HttpServletRequest req) throws IOException {  
  56.         MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;  
  57.             MultipartFile file = request.getFile("file");  
  58.           
  59.         if(file!=null){  
  60.              /** 获取文件的后缀* */  
  61.             String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));  
  62.               
  63.             /** 使用UUID生成文件名称* */  
  64.             String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称  
  65.               
  66.             /** 将文件转化为字节流 **/  
  67.             InputStream inputStream = file.getInputStream();  
  68.               
  69.                 System.out.println("上传图片"+logImageName);  
  70.                   
  71.                 FTPUTIL.upload(inputStream,logImageName, FTPPSTH);  
  72.                   
  73.                 System.out.println("----------------------------->图片上传成功");  
  74.                   
  75.                   
  76.                 return JsonUtil.success();  
  77.             }  
  78.           
  79.   
  80.         return JsonUtil.error("头像上传失败!!!");  
  81.     }  
  82.       
  83.       
  84. }  

ftpUtil

[java]  view plain  copy
  1. package top.yiwei.common.upload;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4.   
  5. import org.apache.commons.net.ftp.FTP;  
  6. import org.apache.commons.net.ftp.FTPClient;  
  7. import org.apache.commons.net.ftp.FTPReply;  
  8.   
  9. /** 
  10.  *  
  11.  * @author Fanqiang 
  12.  * @typeName FtpUtil 
  13.  * @date 2017年6月12日;上午8:02:55 
  14.  */  
  15. public class FtpUtil{  
  16.     private FTPClient ftpClient = null;  
  17.     private String server;  
  18.     private int port;  
  19.     private String userName;  
  20.     private String userPassword;  
  21.   
  22.     public FtpUtil(String server, int port, String userName, String userPassword) {  
  23.         this.server = server;  
  24.         this.port = port;  
  25.         this.userName = userName;  
  26.         this.userPassword = userPassword;  
  27.     }  
  28.   
  29.     /** 
  30.      * 连接服务器 
  31.      * @return 连接成功与否 true:成功, false:失败 
  32.      */  
  33.     public boolean open() {  
  34.         if (ftpClient != null && ftpClient.isConnected()) {  
  35.             return true;  
  36.         }  
  37.         try {  
  38.             ftpClient = new FTPClient();  
  39.             // 连接  
  40.             ftpClient.connect(this.server, this.port);  
  41.             ftpClient.login(this.userName, this.userPassword);  
  42.             setFtpClient(ftpClient);  
  43.             // 检测连接是否成功  
  44.             int reply = ftpClient.getReplyCode();  
  45.             if (!FTPReply.isPositiveCompletion(reply)) {  
  46.                 this.close();  
  47.                 System.err.println("FTP server refused connection.");  
  48.                 System.exit(1);  
  49.             }  
  50.             System.out.println("open FTP success:" + this.server + ";port:" + this.port + ";name:" + this.userName  
  51.                     + ";pwd:" + this.userPassword);  
  52.             ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally  or ascii  
  53.             return true;  
  54.         } catch (Exception ex) {  
  55.             this.close();  
  56.             ex.printStackTrace();  
  57.             return false;  
  58.         }  
  59.     }  
  60.     /** 
  61.      * 选择上传的目录,没有创建目录 
  62.      * @param ftpPath 需要上传、创建的目录 
  63.      * @return 
  64.      */  
  65.     public boolean mkDir(String ftpPath) {  
  66.         if (!ftpClient.isConnected()) {  
  67.             return false;  
  68.         }  
  69.         try {  
  70.             // 将路径中的斜杠统一  
  71.             char[] chars = ftpPath.toCharArray();  
  72.             StringBuffer sbStr = new StringBuffer(256);  
  73.             for (int i = 0; i < chars.length; i++) {  
  74.                 if ('\\' == chars[i]) {  
  75.                     sbStr.append('/');  
  76.                 } else {  
  77.                     sbStr.append(chars[i]);  
  78.                 }  
  79.             }  
  80.             ftpPath = sbStr.toString();  
  81.             System.out.println("ftpPath:" + ftpPath);  
  82.             if (ftpPath.indexOf('/') == -1) {  
  83.                 // 只有一层目录  
  84.                 ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));  
  85.                 ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));  
  86.             } else {  
  87.                 // 多层目录循环创建  
  88.                 String[] paths = ftpPath.split("/");  
  89.                 for (int i = 0; i < paths.length; i++) {  
  90.                     ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1"));  
  91.                     ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));  
  92.                 }  
  93.             }  
  94.             return true;  
  95.         } catch (Exception e) {  
  96.             e.printStackTrace();  
  97.             return false;  
  98.         }  
  99.     }  
  100.     /** 
  101.      * 上传文件到FTP服务器    文件字节流 
  102.      * @param fis 上传的文件字节流 
  103.      * @param ftpFileName 上传到服务器的文件名 
  104.      * @param ftpDirectory 上传到FTP的目录 
  105.      * @return 
  106.      */  
  107.     public boolean upload(InputStream fis, String ftpFileName, String ftpDirectory) {  
  108.         if (!ftpClient.isConnected()) {  
  109.             return false;  
  110.         }  
  111.         boolean flag = false;  
  112.         if (ftpClient != null) {  
  113.             try {  
  114.                 ftpClient.setBufferSize(100000);  
  115.                 ftpClient.setControlEncoding("UTF-8");  
  116.                 // 设置文件类型(二进制)  
  117.                 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
  118.                 // 上传  
  119.                 flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "iso-8859-1"), fis);  
  120.                  
  121.             } catch (Exception e) {  
  122.                 this.close();  
  123.                 e.printStackTrace();  
  124.                 return false;  
  125.             } finally {  
  126.                 try {  
  127.                     fis.close();  
  128.                 } catch (IOException e) {  
  129.                     e.printStackTrace();  
  130.                 }  
  131.             }  
  132.         }  
  133.         System.out.println("上传文件成功,本地文件名: " + ftpFileName + ",上传到目录:" + ftpDirectory + "/" + ftpFileName);  
  134.         return flag;  
  135.     }  
  136.   
  137.     /** 
  138.      * 关闭链接 
  139.      */  
  140.     public void close() {  
  141.         try {  
  142.             if (ftpClient != null && ftpClient.isConnected()) {  
  143.                 ftpClient.disconnect();  
  144.             }  
  145.             System.out.println("成功关闭连接,服务器ip:" + this.server + ", 端口:" + this.port);  
  146.         } catch (Exception e) {  
  147.             e.printStackTrace();  
  148.         }  
  149.     }  
  150.   
  151.     public FTPClient getFtpClient() {  
  152.         return ftpClient;  
  153.     }  
  154.   
  155.     public void setFtpClient(FTPClient ftpClient) {  
  156.         this.ftpClient = ftpClient;  
  157.     }  
  158.   
  159. }  

jsonUtil

[java]  view plain  copy
  1. package top.yiwei.common;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import net.sf.json.JSONObject;  
  7.   
  8. /** 
  9.  * @author 
  10.  * @version 1.0 
  11.  */  
  12. public abstract class JsonUtil {  
  13.   
  14.     private final static String SUCCESS_CODE = "200";  
  15.     private final static String ERROR_CODE = "400";  
  16.   
  17.     private JsonUtil() {  
  18.     }  
  19.   
  20.     /** 
  21.      * @author 
  22.      * @return 
  23.      */  
  24.     public static String success() {  
  25.         Map<String, String> map = new HashMap<String, String>(2);  
  26.         map.put("code", SUCCESS_CODE);  
  27.         return JSONObject.fromObject(map).toString();  
  28.     }  
  29.   
  30.     /** 
  31.      * @author  
  32.      * @param o 
  33.      * @return 
  34.      */  
  35.     public static String success(Object o) {  
  36.         Map<String, Object> map = new HashMap<String, Object>(4);  
  37.         map.put("code", SUCCESS_CODE);  
  38.         map.put("data", o);  
  39.         return JSONObject.fromObject(map).toString();  
  40.     }  
  41.   
  42.     /** 
  43.      * @author 
  44.      * @param msg 
  45.      * @return 
  46.      */  
  47.     public static String error(String msg) {  
  48.         Map<String, String> map = new HashMap<String, String>(4);  
  49.         map.put("code", ERROR_CODE);  
  50.         map.put("msg", msg);  
  51.         return JSONObject.fromObject(map).toString();  
  52.     }  
  53. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值