前台代码:
用了ajaxfileupload.js插件(https://github.com/search?utf8=%E2%9C%93&q=ajaxfileupload.js)

<!--form表单-->
<form name="picForm"
                    action="<@path/>/GoodsManagerCtrl/uploadGoodsPicture" method="post"
                    enctype="multipart/form-data">
                    <button id="up" type="button" class="btn btn-success pull-right"
                        onclick="uploadPicture();">上传图片</button>
                    <input id="pic" type="file" type="file" accept="image/*" name="pic" class="btn" />
                </form>
<script type="text/javascript">
//js代码
        function uploadPicture() {
            jQuery
                    .ajaxFileUpload({
                        url : '<@path/>/GoodsManagerCtrl/uploadGoodsPicture', //用于文件上传的服务器端请求地址
                        secureuri : false, //是否需要安全协议,一般设置为false
                        fileElementId : 'pic', //文件上传域的ID
                        dataType : 'json', //返回值类型 一般设置为json
                        type : 'post',
                        success : function(data) {
                            alert(data.result.key);//后台返回的key
                        },
                        error : function(data) {
                            console.log("错误:" + data);
                        }
                    });
        }
    </script>

controller方法:

@RequestMapping(value = "/uploadGoodsPicture")
    public @ResponseBody Feedback uploadGoodsPicture(
            @RequestParam(value = "pic", required = false) MultipartFile pic)
            throws IllegalStateException, IOException {
        if (null == pic) {
            return "no picture";
        }
        File source = new File(filename.toString());// 文件
        pic.transferTo(source);//MultipartFile 转file
        String fileName = source.getName();
        if (source.isFile()) {
            // 得到File后的操作
            PictureUpload pictureUpload = new PictureUpload();
            try {
                String msg = pictureUpload.upload(source,
                        "pctureName.png");//核心:调用下面PictureUpload的方法①
                JSONObject jsStr = new JSONObject(msg); // 反序列化
                String key = (String) jsStr.get("key");
                return Feedback.success("查询成功", key);
            } catch (IOException e) {
                e.printStackTrace();
                return Feedback.error("上传失败");
            }
            // TODO
        }
        return null;
    }
package com.bysj.common.picture;
import java.io.File;
import java.io.IOException;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
public class PictureUpload {

      String ACCESS_KEY = "rYh6SJlnCN-n_Ue_pa0TEFvjn4LwG-******";
      String SECRET_KEY = "i9onpvo6SQQox-WvY5rkEhhRMumM*******";
      //要上传的空间
      String bucketname = "glgl";

      //密钥配置
      Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
      //创建上传对象
      UploadManager uploadManager = new UploadManager();
      //简单上传,使用默认策略,只需要设置上传的空间名就可以了
      public String getUpToken(){
          return auth.uploadToken(bucketname);
      }

    //①上传方法controller调用
      public String upload(File uploadPictureFile,String  pictureName) throws IOException{
            try {
              //调用put方法上传
              Response res = uploadManager.put(uploadPictureFile, pictureName, getUpToken());
              //打印返回的信息
              return res.bodyString();
              } catch (QiniuException e) {
                  Response r = e.response;
                  // 请求失败时打印的异常的信息
                  System.out.println(r.toString());
                  try {
                      //响应的文本信息
                    System.out.println(r.bodyString());
                  } catch (QiniuException e1) {
                      //ignore
                  }
                  return null;
              }
          }
}

{code: 200, msg: "查询成功", result: "pic11483876792783", success: true}

上传成功后前台得到图片名称,到七牛云-对象存储-存储空间列表(glgl)-内容管理,输入“pic11483876792783”搜索上传成功的图片

小弟初学,愿多交流

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐