SpringBoot的文件上传和下载、二维码

在Ideal环境下创建一个SpringBoot项目,客户端文件上传、下载和二维码生成的功能。

(1)在下列主界面中通过点击超链接分别进入进入文件上传页面、文件下载页面和二维码生成页面。

(2)在下列文件上传页面中,选择要上传的文件,点击提交按钮,则将选择的文件上传到服务器指定的目录下。

(3)在下列文件下载页面中,点击下列超链接,则将超链接的文件下载到客户端指定的目录下。

(4)在下列二维码生成页面中,点击“生成二维码“按钮,则二维码输出到客户端。

项目:

链接:

防封,wwm.lanzn.com/insm91z9j8wf   ,,

效果如下:

主页如下:

文件上传页面:

注意,我没有test目录,我修改到"E:/test":

点击提交后:

文件下载页面:

点击下载后:

二维码页面,二维码为百度:

扫描后:

项目如下:

核心代码:

MyController.java:

package spring.demo;

import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.util.List;

@Controller
public class MyController {
    //获取主机地址和主机名
    public String getAddress() {
        try {
            InetAddress add = InetAddress.getLocalHost();
            return "主机地址:" + add.getHostAddress() + "主机名:" + add.getHostName();
        } catch (Exception ex) {
            ex.printStackTrace();
            return "无法获取地址 ";
        }
    }

    //获取主页面mainfile.htm1
    @RequestMapping("/")
    public String mainfile(Model model) {
        model.addAttribute("backMessage", getAddress());
        return "/mainfile";
    }

    @RequestMapping("multifile")
    public String multifile(Model model){
        model.addAttribute("backMessage", getAddress());
        return "/multifile";
    }
    // 实现多文件上传
    @RequestMapping("/multifileUpload")
    //4.设置请求映射的参数(与客户端访问的URL地址关联)
    public @ResponseBody String multifileUpload(
            @RequestParam("fileName") List<MultipartFile> files,
            HttpServletRequest request) {
        if (files.isEmpty()) {
            return "没有要上传的文件";
        }
        String path = "E:/test";
        int i = 0;
        String backMes = "";
        for (MultipartFile file : files) {
            i++;
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);
            if (file.isEmpty()) {
                //5,将"第?个文件上传为空\n"字符串累加到backMes变量中
                backMes+="第"+i+"个文件上传为空\n";
            }
            else {
                File dest = new File(path + "/" + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                    backMes+="第"+i+"个文件上传成功\n";
                } catch (Exception e) {
                    e.printStackTrace();
                    return "第" + i + "个文件上传失败";
                }
            }
        }
        return backMes;
    }

    @RequestMapping("/downfile")
    public String downFile(Model model){
        model.addAttribute("backMessage", getAddress());
        return "/downfile";
    }

    @RequestMapping("/download")
    public String downLoad(HttpServletResponse response,String filename){
        String filePath = "E:/test";
        File file = new File(filePath+"/"+filename);
        if ((file.exists())){
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition","attachment;fileName="+filename);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream os = null;
            try{
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("------------file download   " + filename);
            try {
                bis.close();
                fis.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("/QRfile")
    public String Qrfile(Model model){
        model.addAttribute("backMessage", getAddress());
        return "/QRfile";
    }

    @RequestMapping("/QRCode")
    public void qrCode(HttpServletResponse response) throws WriteAbortedException, IOException, WriterException {
        Qrkit.createZxing(response,100,100,20,"H","jpg","www.baidu.com");
    }

}

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要生成微信支付二维码,可以使用微信支付官方提供的接口,以下是基于 Spring Boot 的简单实现步骤: 1. 引入相关依赖 ```xml <dependency> <groupId>com.github.wxpay</groupId> <artifactId>wxpay-sdk</artifactId> <version>3.0.9</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> </dependency> ``` 2. 配置微信支付相关参数 ```java @Configuration public class WxPayConfig { // 微信支付分配的商户号 @Value("${wxpay.mchId}") private String mchId; // 微信支付分配的终端设备号 @Value("${wxpay.deviceInfo}") private String deviceInfo; // 微信支付分配的公众账号ID @Value("${wxpay.appId}") private String appId; // 微信支付分配的商户密钥 @Value("${wxpay.key}") private String key; // 微信支付异步通知地址 @Value("${wxpay.notifyUrl}") private String notifyUrl; // 微信支付统一下单接口地址 @Value("${wxpay.unifiedOrderUrl}") private String unifiedOrderUrl; // 微信支付查询订单接口地址 @Value("${wxpay.orderQueryUrl}") private String orderQueryUrl; // 微信支付关闭订单接口地址 @Value("${wxpay.closeOrderUrl}") private String closeOrderUrl; // 微信支付申请退款接口地址 @Value("${wxpay.refundUrl}") private String refundUrl; // 微信支付查询退款接口地址 @Value("${wxpay.refundQueryUrl}") private String refundQueryUrl; // 微信支付下载对账单接口地址 @Value("${wxpay.downloadBillUrl}") private String downloadBillUrl; // 微信支付交易保障接口地址 @Value("${wxpay.reportUrl}") private String reportUrl; // 签名类型 private final String SIGN_TYPE = "MD5"; // 连接超时时间 private final int CONNECT_TIMEOUT = 5000; // 读取超时时间 private final int READ_TIMEOUT = 10000; // 微信支付API证书路径 @Value("${wxpay.certPath}") private String certPath; // 微信支付API证书密码 @Value("${wxpay.certPassword}") private String certPassword; /** * 初始化微信支付配置 */ @Bean public WXPay wxPay() throws Exception { WXPayConfigImpl config = new WXPayConfigImpl(); config.setAppID(appId); config.setMchID(mchId); config.setKey(key); config.setDeviceInfo(deviceInfo); config.setSignType(SIGN_TYPE); config.setUnifiedOrderUrl(unifiedOrderUrl); config.setOrderQueryUrl(orderQueryUrl); config.setCloseOrderUrl(closeOrderUrl); config.setRefundUrl(refundUrl); config.setRefundQueryUrl(refundQueryUrl); config.setDownloadBillUrl(downloadBillUrl); config.setReportUrl(reportUrl); return new WXPay(config, notifyUrl, true, true); } /** * 微信支付配置类 */ class WXPayConfigImpl extends WXPayConfig { private String appId; private String mchId; private String key; private String deviceInfo; private String signType; private String unifiedOrderUrl; private String orderQueryUrl; private String closeOrderUrl; private String refundUrl; private String refundQueryUrl; private String downloadBillUrl; private String reportUrl; public void setAppID(String appId) { this.appId = appId; } public void setMchID(String mchId) { this.mchId = mchId; } public void setKey(String key) { this.key = key; } public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } public void setSignType(String signType) { this.signType = signType; } public void setUnifiedOrderUrl(String unifiedOrderUrl) { this.unifiedOrderUrl = unifiedOrderUrl; } public void setOrderQueryUrl(String orderQueryUrl) { this.orderQueryUrl = orderQueryUrl; } public void setCloseOrderUrl(String closeOrderUrl) { this.closeOrderUrl = closeOrderUrl; } public void setRefundUrl(String refundUrl) { this.refundUrl = refundUrl; } public void setRefundQueryUrl(String refundQueryUrl) { this.refundQueryUrl = refundQueryUrl; } public void setDownloadBillUrl(String downloadBillUrl) { this.downloadBillUrl = downloadBillUrl; } public void setReportUrl(String reportUrl) { this.reportUrl = reportUrl; } @Override public String getAppID() { return appId; } @Override public String getMchID() { return mchId; } @Override public String getKey() { return key; } @Override public InputStream getCertStream() { try { return new FileInputStream(new File(certPath)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } @Override public int getHttpConnectTimeoutMs() { return CONNECT_TIMEOUT; } @Override public int getHttpReadTimeoutMs() { return READ_TIMEOUT; } @Override public String getDeviceInfo() { return deviceInfo; } @Override public String getSignType() { return signType; } @Override public String getUnifiedOrderUrl() { return unifiedOrderUrl; } @Override public String getOrderQueryUrl() { return orderQueryUrl; } @Override public String getCloseOrderUrl() { return closeOrderUrl; } @Override public String getRefundUrl() { return refundUrl; } @Override public String getRefundQueryUrl() { return refundQueryUrl; } @Override public String getDownloadBillUrl() { return downloadBillUrl; } @Override public String getReportUrl() { return reportUrl; } } } ``` 3. 调用微信支付统一下单接口,获取支付二维码 ```java @RestController @RequestMapping("/wxpay") public class WxPayController { @Autowired private WXPay wxPay; /** * 生成微信支付二维码 * * @param orderId 订单ID * @param amount 支付金额 * @return 二维码图片Base64编码字符串 */ @GetMapping("/qrcode") public String generateQrCode(@RequestParam("order_id") String orderId, @RequestParam("amount") int amount) { try { Map<String, String> data = new HashMap<>(); data.put("body", "xxxx"); // 商品描述 data.put("out_trade_no", orderId); // 订单号 data.put("total_fee", String.valueOf(amount)); // 支付金额,单位为分 data.put("spbill_create_ip", "127.0.0.1"); // 发起支付的客户端IP data.put("notify_url", "http://localhost/wxpay/notify"); // 支付成功的回调地址 data.put("trade_type", "NATIVE"); // 交易类型,JSAPI:公众号支付;NATIVE:扫码支付;APP:APP支付 data.put("product_id", orderId); // 商品ID,trade_type=NATIVE时必填 // 调用微信支付统一下单接口 Map<String, String> result = wxPay.unifiedOrder(data); String return_code = result.get("return_code"); String result_code = result.get("result_code"); if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) { String codeUrl = result.get("code_url"); // 生成二维码 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BitMatrix bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 300, 300); MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream); byte[] bytes = outputStream.toByteArray(); return Base64.getEncoder().encodeToString(bytes); } else { String err_code_des = result.get("err_code_des"); throw new RuntimeException(err_code_des); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } } ``` 以上就是基于 Spring Boot 的微信支付二维码生成的简单实现了。需要注意的是,微信支付二维码的有效期为2小时,超过时间后需要重新生成。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值